Lesson 17 / 32
Rooms and Broadcasting
Track which sockets belong to which room, broadcast to a room, and clean up when sockets close.
By Rahul Agarwal · 15 years in web development
Rooms are just sets
Group chat, a live match page or a shared document all need rooms (also called channels or topics): send this message to everyone interested in X. On a single server, a room is simply a Map from room name to a Set of sockets. Joining adds the socket; broadcasting loops over the set and sends to each socket whose readyState is OPEN, usually skipping the sender, who already shows the message optimistically. The part beginners forget is cleanup: on close, remove the socket from every room it joined and delete empty rooms, or the map grows with dead sockets and broadcasts slow down. Also check authorisation on join: being able to name a room must not mean being allowed to read it. This in-memory design breaks as soon as you run two server processes, because a user on server A cannot see sockets held by server B; Section 7 solves that with a pub/sub broker.
Two rooms, three clients
Asha and Ravi join the same room; Meera joins another. Only Ravi receives Asha's message: the sender is skipped, and Meera is in a different room.
import { WebSocketServer, WebSocket } from 'ws';
const rooms = new Map(); // roomName -> Set<WebSocket>
function join(room, socket) {
if (!rooms.has(room)) rooms.set(room, new Set());
rooms.get(room).add(socket);
socket.room = room;
}
function leave(socket) {
const members = rooms.get(socket.room);
if (!members) return;
members.delete(socket);
if (members.size === 0) rooms.delete(socket.room);
}
function broadcast(room, message, except) {
for (const client of rooms.get(room) ?? []) {
if (client !== except && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(message));
}
}
}
const wss = new WebSocketServer({ port: 8081 });
wss.on('connection', (socket) => {
socket.on('message', (raw) => {
const msg = JSON.parse(raw);
if (msg.type === 'join') join(msg.room, socket);
if (msg.type === 'chat') broadcast(socket.room, { from: msg.from, text: msg.text }, socket);
});
socket.on('close', () => leave(socket));
});
// --- demo: three clients, two rooms ---
const open = (name, room) =>
new Promise((resolve) => {
const ws = new WebSocket('ws://localhost:8081');
ws.on('open', () => {
ws.send(JSON.stringify({ type: 'join', room }));
resolve(ws);
});
ws.on('message', (data) => console.log(`${name} received ${data}`));
});
const asha = await open('asha', 'cse-2nd-year');
const ravi = await open('ravi', 'cse-2nd-year');
const meera = await open('meera', 'ece-3rd-year');
await new Promise((r) => setTimeout(r, 50));
asha.send(JSON.stringify({ type: 'chat', from: 'asha', text: 'lab at 3?' }));
await new Promise((r) => setTimeout(r, 50));
for (const ws of [asha, ravi, meera]) ws.close();
wss.close();
Output:
ravi received {"from":"asha","text":"lab at 3?"}Class WhatsApp groups
A room is a WhatsApp group for one class section. The server is the admin's list of members: posting in "CSE 2nd year" reaches only that list, and when someone leaves college, they must be removed from every group or messages keep piling up for nobody.
Serialise once, send many
When broadcasting to thousands of sockets, call JSON.stringify once outside the loop, not once per client. Serialising the same object repeatedly is a common hidden CPU cost.
Quick check: In the in-memory rooms design, what goes wrong if `close` does not remove the socket from its rooms?
- Dead sockets accumulate, leaking memory and slowing broadcasts
- The client cannot reconnect
- The room is automatically deleted
- Messages are delivered twice to every client
Answer
Dead sockets accumulate, leaking memory and slowing broadcasts — The Set keeps references to closed sockets. Memory grows and every broadcast iterates over clients that can never receive anything.