Gestire stanze e canali
Organizzi i client WebSocket in stanze e canali, così i messaggi raggiungono solo il gruppo interessato: la base delle app di chat e collaborazione.
Gestire stanze e canali è una lezione WebSockets & Realtime Systems Programming 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 WebSockets & Realtime Systems Programming, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso WebSockets & Realtime Systems Programming include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Why Rooms
Broadcasting to everyone does not scale for multi-topic apps. Rooms (or channels) let you group clients so a message only reaches members of one group, like a single chat room.
Modeling Rooms
A simple model maps a room name to a set of client connections.
const rooms = new Map(); // roomName -> Set<ws>Joining a Room
When a client asks to join, add its connection to that room set, creating the set on first use.
function join(room, ws) {
if (!rooms.has(room)) rooms.set(room, new Set());
rooms.get(room).add(ws);
}Leaving a Room
Remove the connection on leave, and clean up empty rooms to avoid leaks.
function leave(room, ws) {
const set = rooms.get(room);
if (!set) return;
set.delete(ws);
if (set.size === 0) rooms.delete(room);
}A Join Message Protocol
Clients signal intent with structured messages. Parse the type and route accordingly.
ws.on('message', (raw) => {
const msg = JSON.parse(raw);
if (msg.type === 'join') join(msg.room, ws);
});Broadcasting to a Room
To send to a room, iterate only that room set, skipping closed sockets.
function toRoom(room, payload) {
const set = rooms.get(room);
if (!set) return;
for (const client of set) {
if (client.readyState === 1) client.send(payload);
}
}Tracking a Client\u2019s Rooms
Store room membership on the connection so cleanup on disconnect is easy.
ws.rooms = new Set();Cleaning Up on Disconnect
When a socket closes, remove it from every room it joined.
ws.on('close', () => {
for (const room of ws.rooms) leave(room, ws);
});Channels vs Rooms
Terms vary. Often a channel is a named topic clients subscribe to, while a room is a private group. Mechanically both are just keyed sets of subscribers.
Presence Awareness
You can derive presence from room membership: the size of a room set is the number of online members, and join/leave events can notify others.
toRoom(room, JSON.stringify({ type: 'presence', count: rooms.get(room).size }));Best Practices
Keep room management robust:
- Always clean up on disconnect
- Skip sockets not in OPEN state
- Validate room names from clients
- Remove empty rooms to free memory
Quick Check
Test your rooms knowledge.
Recap
You added rooms to your WebSocket server:
- Map room names to sets of connections
- Handle join/leave via structured messages
- Broadcast only to a room\u2019s members
- Clean up on disconnect and derive presence
This is the backbone of chat and collaboration features.
Domande Frequenti
La lezione «Gestire stanze e canali» è gratuita?
Sì — il testo completo di «Gestire stanze e canali» è 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 WebSockets & Realtime Systems Programming, passa a CoddyKit PRO. Il corso WebSockets & Realtime Systems Programming include 4 lezioni in totale.
Cosa imparerò in «Gestire stanze e canali»?
Organizzi i client WebSocket in stanze e canali, così i messaggi raggiungono solo il gruppo interessato: la base delle app di chat e collaborazione. Eserciti WebSockets & Realtime Systems Programming 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 WebSockets & Realtime Systems Programming?
Non è richiesta alcuna esperienza precedente. WebSockets & Realtime Systems Programming 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 «Gestire stanze e canali»?
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 WebSockets & Realtime Systems Programming?
Sì. Ogni lezione WebSockets & Realtime Systems Programming 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
- Configurare un progetto Node.js
- Implementare la logica lato server
- Trasmettere messaggi ai client
- Gestire stanze e canali