使用 Phoenix Channels 实现实时功能
通过 WebSockets 上的 Channels,为 Phoenix 应用添加双向实时通信。
使用 Phoenix Channels 实现实时功能 是 CoddyKit 上的免费 Elixir & Phoenix: Scalable Backend Development 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Elixir & Phoenix: Scalable Backend Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Elixir & Phoenix: Scalable Backend Development 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What Are Channels?
Phoenix Channels provide a real-time, bidirectional messaging layer over WebSockets (with fallbacks). Perfect for chat, notifications, and live dashboards.
The Socket Layer
Clients connect to a Socket, which authenticates the connection and routes to topics. It is defined in your endpoint.
socket "/socket", MyAppWeb.UserSocket,
websocket: true,
longpoll: falseDefining a UserSocket
The socket module declares which channels handle which topic patterns and how to connect.
defmodule MyAppWeb.UserSocket do
use Phoenix.Socket
channel "room:*", MyAppWeb.RoomChannel
def connect(_params, socket, _info), do: {:ok, socket}
def id(_socket), do: nil
endTopics and Subscriptions
A topic is a string like room:lobby. Clients join a topic to send and receive messages scoped to it.
Creating a Channel
A channel module handles join and incoming events with handle_in.
defmodule MyAppWeb.RoomChannel do
use MyAppWeb, :channel
def join("room:" <> _id, _params, socket) do
{:ok, socket}
end
endHandling Incoming Messages
handle_in/3 reacts to events pushed by clients. Return :noreply or reply to the sender.
def handle_in("new_msg", %{"body" => body}, socket) do
broadcast!(socket, "new_msg", %{body: body})
{:noreply, socket}
endBroadcasting to a Topic
broadcast!/3 sends a message to EVERY subscriber of the topic, enabling real-time fan-out.
broadcast!(socket, "new_msg", %{body: "Hello everyone"})Replying to the Sender
Return {:reply, {:ok, payload}, socket} to answer only the client that sent the event.
def handle_in("ping", _payload, socket) do
{:reply, {:ok, %{pong: true}}, socket}
endPushing from the Server
Use push/3 to send a message to one connected client, for example after async work completes.
push(socket, "notification", %{text: "Job finished"})The JavaScript Client
On the front end, the Phoenix JS client connects, joins a topic, and listens for events.
let channel = socket.channel("room:lobby", {})
channel.join()
channel.on("new_msg", payload => console.log(payload.body))Presence Tracking
Phoenix.Presence builds on Channels to track who is online across the cluster, syncing join and leave events automatically.
Quick Check
Test your Channels knowledge.
Recap
You added real-time features with Channels:
- Clients connect to a Socket and join topics
- Channels handle
joinandhandle_inevents broadcast!fans out,push/replytarget one client- Presence tracks online users on top of Channels
常见问题解答
「使用 Phoenix Channels 实现实时功能」课时是免费的吗?
是的 — 「使用 Phoenix Channels 实现实时功能」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Elixir & Phoenix: Scalable Backend Development 课程的其余内容,请升级到 CoddyKit PRO。 Elixir & Phoenix: Scalable Backend Development 课程共包含 4 节课。
「使用 Phoenix Channels 实现实时功能」这节课中我会学到什么?
通过 WebSockets 上的 Channels,为 Phoenix 应用添加双向实时通信。 你通过在浏览器中直接运行的动手代码来练习 Elixir & Phoenix: Scalable Backend Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Elixir & Phoenix: Scalable Backend Development 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Elixir & Phoenix: Scalable Backend Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「使用 Phoenix Channels 实现实时功能」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Elixir & Phoenix: Scalable Backend Development 课中编写并运行代码吗?
能。每节 Elixir & Phoenix: Scalable Backend Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Phoenix 项目设置与结构
- 路由、控制器与 Plugs
- 视图、模板与 LiveView 基础
- 使用 Phoenix Channels 实现实时功能