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.