CodeBlanks Logo Icon CodeBlanks

Broadcast

Learn to broadcast to all clients.

What is broadcast?

Broadcast means sending a message to all connected clients. In a chat app, when a user types a message the server relays it to everyone; that is a broadcast.

In the ws module you broadcast with wss.clients. wss.clients is a Set that holds all connected clients. You send to everyone with wss.clients.forEach((client) => { client.send(msg); }). Some clients may be closed; you send only to open ones by checking client.readyState === 1.

The broadcast pattern

The typical broadcast pattern: a message arrives from one client, the server relays it to all other clients. ws.on("message", (data) => { wss.clients.forEach((client) => { if (client !== ws && client.readyState === 1) { client.send(data); } }); }).

The client !== ws check prevents sending the message back to the sender. readyState === 1 sends only to open connections. This pattern is the foundation of chat-room logic. For more complex scenarios you need to group clients into rooms; this is easier in Socket.io.

Practice Log the client count

Create an empty Set (new Set()). Log .size.

Starter code

index.js
// create an empty Set

// log its size

Sample solution

index.js
const clients = new Set();
console.log(clients.size);

Expected output

0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the property name

Question
wss.____.forEach((client) => client.send(msg))
Answer
wss.clients.forEach((client) => client.send(msg))

Explanation: wss.clients is a Set of all connected clients.

2 Match each piece to its role

Term Meaning
wss.clients All clients
forEach Iterates each
client.send Sends a message
readyState === 1 Open connection

3 Which data structure is used for broadcast?

  • Set (wss.clients) Correct answer
  • Number
  • Array
  • String

Explanation: wss.clients is a Set; you iterate with forEach.

All lessons in Advanced