How do you broadcast messages to multiple clients?
Answer
Broadcasting sends a message to multiple clients simultaneously. In raw WebSocket (Node.js ws library): wss.clients.forEach(client => { if (client !== sender && client.readyState === WebSocket.OPEN) { client.send(message); } }). The check client !== sender excludes the sending client. In Socket.IO, broadcasting is built-in: socket.broadcast.emit('event', data) sends to all except sender; io.emit('event', data) sends to all including sender; io.to('room').emit('event', data) sends to a specific room. For targeted broadcast (e.g., send to all sessions of a specific user), maintain a Map<userId, Set<WebSocket>> for users with multiple open connections. Broadcasting should be asynchronous — avoid blocking the event loop by sending to thousands of clients synchronously.
Previous
How do you handle binary data over WebSockets?
Next
What are the security considerations for WebSocket connections?
More WebSockets & Real-time Questions
View all →- Intermediate How do you implement a WebSocket server in Node.js using the `ws` library?
- Intermediate What are Socket.IO rooms and namespaces?
- Intermediate How do you handle WebSocket reconnection logic?
- Intermediate What is the difference between Socket.IO and raw WebSockets?
- Intermediate How do you authenticate WebSocket connections?