# Broadcasting and Rooms

A ws server broadcasts by sending one message to every open client in wss.clients, greets a client who connects late with the current state, keeps rooms as a Map of Sets so a message reaches only one group and cleans up when a client closes, and is tested with real ws clients on a port the test picks.

Journeyman · Node.js · Web Development · Updated November 19, 2026

By Gregor Dzierzon

## After this lesson you can

- Broadcast a message to every open client in wss.clients, and send a client who connects late the current state
- Keep rooms in a Map of Sets, send a message to one room's clients only, and remove a client from its room when it closes
- Test a ws server with node --test, connecting real ws clients on a port the test picks and closing them after each test

## Key takeaways

- wss.clients holds every connected client. A broadcast loops over it and sends the same text to each client whose readyState is WebSocket.OPEN.
- A client who connects late has missed every earlier message, so send it the current state as soon as it connects.
- A room is a group of clients that get the same messages. A Map from each room's name to a Set of its clients keeps them, and a client leaves its room when it closes.
- Socket.IO is a library that adds rooms and automatic reconnects, but both sides must use it. ws speaks the plain WebSocket protocol that every browser knows.
- A test starts the server on port 0, so the computer picks a free port, connects real ws clients to it, and closes every one of them after each test.

A chat message goes to everyone in the chat, a new score to everyone watching, and "someone is typing" only to the people in that conversation. Deciding who gets each message is most of the work in any live feature, and it's where live bugs hide: the message that reached the wrong group, or a fan who left but is still on the list.

In *A First WebSocket Connection*, Hilltop's server counted cheers, but only the fan who tapped saw the new count. This lesson sends it to everyone, then splits the fans by game.

## One cheer, every fan

`socket.send` reaches one client. The server also keeps every connected client in `wss.clients`, a `Set` that ws adds each client to when it connects and takes it out of when it closes. Sending the same message to all of them is called **broadcasting**:

```javascript
function broadcast(message) {
  const text = JSON.stringify(message);
  for (const client of wss.clients) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(text);
    }
  }
}
```

`readyState` says where a line is: `WebSocket.OPEN` means it's ready to send, while a line that's still closing isn't, so the check skips it. Import `WebSocket` with the server, `import { WebSocketServer, WebSocket } from "ws"`.

Now the message listener broadcasts the new count, and an error still goes only to the fan whose message caused it. One more rule: a fan who opens the page in the second half has missed every earlier message, so the server sends a newcomer the current count the moment they connect:

```javascript
wss.on("connection", (socket) => {
  socket.send(JSON.stringify({ type: "cheers", hawks: cheers.hawks, foxes: cheers.foxes }));

  socket.on("message", (data) => {
    const answer = reply(cheers, data.toString());
    if (answer.type === "error") {
      socket.send(JSON.stringify(answer));
    } else {
      broadcast(answer);
    }
  });
});
```

## Rooms: one group for each game

On Saturdays, Hilltop plays on two fields at once. A fan following Field 2 doesn't want Field 1's cheers. A **room** is a named group of clients that get the same messages: one room for each field.

Two collections you know already do it. A `Map` finds a value by its key, so it finds a room's fans by the room's name. A `Set` holds each fan once and removes one quickly. So the rooms are a Map of Sets. This program shows it with plain objects standing in for fans' lines:

```javascript
const rooms = new Map();

function join(room, fan) {
  if (!rooms.has(room)) {
    rooms.set(room, new Set());
  }
  rooms.get(room).add(fan);
}

function leave(room, fan) {
  const fans = rooms.get(room);
  if (fans === undefined) {
    return;
  }
  fans.delete(fan);
  if (fans.size === 0) {
    rooms.delete(room);
  }
}

const maya = { name: "Maya" };
const theo = { name: "Theo" };
const priya = { name: "Priya" };

join("field-1", maya);
join("field-1", theo);
join("field-2", priya);
console.log([...rooms.keys()]);
console.log(rooms.get("field-1").size);

leave("field-1", theo);
leave("field-2", priya);
console.log([...rooms.keys()]);
console.log(rooms.get("field-1").size);
```

```text
[ 'field-1', 'field-2' ]
2
[ 'field-1' ]
1
```

`[...rooms.keys()]` (the `...` is read "spread") lays the Map's keys out in an array, so you can see them. When the last fan leaves Field 2, `leave` deletes the room itself, so empty rooms don't pile up.

## Cleaning up when a fan leaves

In the server, each line remembers its room in a variable of its own. A `join` message puts the line in a room, a cheer goes only to that room, and the `close` event takes the line back out, so the room never holds a line that's gone:

```javascript
wss.on("connection", (socket) => {
  let room = null;

  socket.on("message", (data) => {
    const message = JSON.parse(data.toString());
    if (message.type === "join") {
      room = message.room;
      join(room, socket);
    } else if (message.type === "cheer") {
      sendToRoom(room, { type: "cheer", team: message.team });
    }
  });

  socket.on("close", () => {
    if (room !== null) {
      leave(room, socket);
    }
  });
});
```

`sendToRoom` is `broadcast` with one change: it loops over `rooms.get(room)` instead of `wss.clients`, and does nothing when the room isn't there. (The listener is short to show the rooms; a real one keeps the `try` and the error messages from *A First WebSocket Connection*.)

![Rooms as a Map of Sets: the Map's key field-1 holds a Set with Maya and Theo, and the key field-2 holds a Set with Priya. Maya's cheer for the Hawks goes to Maya and Theo in field-1, and Priya in field-2 gets nothing.](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/651e4edfdbcb4a939ac7e0b62481fea3.webp)

## Socket.IO: rooms and reconnects built in

Many Node projects use **Socket.IO** (4.8.4 today), a library on top of WebSockets. It has rooms built in, and when a phone loses its signal, its page connects again by itself. The catch: both sides must use it, so the page loads Socket.IO's browser library, and a plain `WebSocket` can't connect to a Socket.IO server. ws speaks the plain protocol every browser knows, and it's small enough that you can see every message, which is why this course uses it. When you meet `io.on("connection")` and `socket.join(room)` in a project, you'll recognize the same ideas.

## Testing with real clients

Supertest sends HTTP requests, but a WebSocket needs a real connection, so the test starts a real server and connects real ws clients to it. ws is a client as well as a server: `new WebSocket(address)` from the `ws` package opens a line from Node. Three habits keep these tests reliable:

- **Let the computer pick the port.** `server.listen(0)` asks for any free port, and `server.address().port` reads which one it got, so a test never fights another program for 3100.
- **Collect messages from the start.** The welcome count can arrive in the same moment the line opens, so add the `message` listener before waiting for `open`.
- **Close everything after each test.** A client left open keeps the test run from finishing.

```javascript
import { test, beforeEach, afterEach } from "node:test";
import assert from "node:assert/strict";
import http from "node:http";
import { once } from "node:events";
import { setTimeout as delay } from "node:timers/promises";
import { WebSocket } from "ws";
import { attachCheers } from "./cheers.js";

let server;
let clients;

beforeEach(async () => {
  server = http.createServer();
  attachCheers(server);
  server.listen(0);
  await once(server, "listening");
  clients = [];
});

afterEach(async () => {
  for (const client of clients) {
    client.close();
    await once(client, "close");
  }
  server.close();
});

async function connect() {
  const client = new WebSocket(`ws://localhost:${server.address().port}`);
  client.received = [];
  client.on("message", (data) => client.received.push(JSON.parse(data.toString())));
  clients.push(client);
  await once(client, "open");
  return client;
}

test("1) A cheer from Maya reaches Theo too: hawks 1, foxes 0", async () => {
  const maya = await connect();
  const theo = await connect();

  maya.send(JSON.stringify({ type: "cheer", team: "hawks" }));
  await delay(100);

  assert.deepEqual(theo.received, [
    { type: "cheers", hawks: 0, foxes: 0 },
    { type: "cheers", hawks: 1, foxes: 0 },
  ]);
});
```

`attachCheers(server)` is the code above in a module, `cheers.js`, that starts the `WebSocketServer` on the server it's given, with its own `cheers`, so every test starts from 0. `once(emitter, name)` waits for one event, and `delay(100)` gives the messages a tenth of a second to arrive. `npm test` runs it:

```text
✔ 1) A cheer from Maya reaches Theo too: hawks 1, foxes 0 (138.6475ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 227.0393
```

Your times will differ.

## Check yourself

2 questions to try on the lesson page.

## So what

Every live feature comes down to who gets each message: everyone, one room, or only the sender, and a test with real clients is how you prove the right people got it.

## Key terms

- [Broadcast](https://www.ask-codey.com/glossary/broadcast)
- [WebSocket Room](https://www.ask-codey.com/glossary/websocket-room)
- [Map](https://www.ask-codey.com/glossary/map-javascript-2)
- [Set](https://www.ask-codey.com/glossary/set-javascript)
- [Socket.IO](https://www.ask-codey.com/glossary/socket-io)
- [node:test](https://www.ask-codey.com/glossary/node-test)

## Related

- [A First WebSocket Connection](https://www.ask-codey.com/lessons/node-websockets-first-connection)
- [Testing an API with Supertest](https://www.ask-codey.com/lessons/node-testing-supertest)

Source: https://www.ask-codey.com/lessons/node-websockets-broadcasting
