Funzionalità in tempo reale con Phoenix Channels
Aggiunga comunicazioni bidirezionali in tempo reale alla sua app Phoenix usando i Channels tramite WebSocket.
Funzionalità in tempo reale con Phoenix Channels è una lezione Elixir & Phoenix: Scalable Backend Development gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Elixir & Phoenix: Scalable Backend Development, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Elixir & Phoenix: Scalable Backend Development include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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
Domande Frequenti
La lezione «Funzionalità in tempo reale con Phoenix Channels» è gratuita?
Sì — il testo completo di «Funzionalità in tempo reale con Phoenix Channels» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Elixir & Phoenix: Scalable Backend Development, passa a CoddyKit PRO. Il corso Elixir & Phoenix: Scalable Backend Development include 4 lezioni in totale.
Cosa imparerò in «Funzionalità in tempo reale con Phoenix Channels»?
Aggiunga comunicazioni bidirezionali in tempo reale alla sua app Phoenix usando i Channels tramite WebSocket. Eserciti Elixir & Phoenix: Scalable Backend Development con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Elixir & Phoenix: Scalable Backend Development?
Non è richiesta alcuna esperienza precedente. Elixir & Phoenix: Scalable Backend Development su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Funzionalità in tempo reale con Phoenix Channels»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Elixir & Phoenix: Scalable Backend Development?
Sì. Ogni lezione Elixir & Phoenix: Scalable Backend Development include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Configurazione e struttura di un progetto Phoenix
- Routing, controller e plug
- View, template e basi di LiveView
- Funzionalità in tempo reale con Phoenix Channels