const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { wss.clients.forEach(function each(client) { if (client.readyState === WebSocket.OPEN) { client.send(message); } }); }); });
The server loops through all connected clients and sends the received message to each one that is open. This means every client connected at that moment gets the message.
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', ws => { ws.on('message', message => { wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) { client.send(message) } }); }); });
Missing semicolon after client.send(message) can cause issues in some JavaScript environments.
wss.on('connection', ws => { ws.on('message', message => { wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) { client.send(message); } }); }); });
The server's wss.clients set includes all clients, but some may be closed. The readyState check prevents sending to closed clients, but if the server does not clean up properly, it may cause issues.
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send('Hello');
}
});Sending a message over WebSocket does not change the connection state. Clients remain OPEN unless explicitly closed.
Sending messages to many clients simultaneously can increase CPU and memory usage on the server, potentially causing delays or crashes if not managed properly.
