Can I broadcast to all WebSocket clients

WebSockets uses TCP, which is point to point, and provides no broadcast support.


Not sure how is your client/server setup, but you can always just keep in the server a collection of all connected clients - and then iterate over each one and send the message.

A simple example using Node's Websocket library:

Server code

var WebSocketServer = require('websocket').server;

var clients = [];
var socket = new WebSocketServer({
  httpServer: server,
  autoAcceptConnections: false
});

socket.on('request', function(request) {
  var connection = request.accept('any-protocol', request.origin);
  clients.push(connection);

  connection.on('message', function(message) {
    //broadcast the message to all the clients
    clients.forEach(function(client) {
      client.send(message.utf8Data);
    });
  });
});

As noted in other answers, WebSockets don't support multicast, but it looks like the 'ws' module maintains a list of connected clients for you, so it's pretty easy to iterate through them. From the docs:

const WebSocketServer = require('ws').Server;
const wss = new WebSocketServer({ port: 8080 });

wss.broadcast = function(data) {
  wss.clients.forEach(client => client.send(data));
};

Yes, it is possible to broadcast messages to multiple clients.

In Java,

  @OnMessage
  public void onMessage(String m, Session s) throws IOException {
  for (Session session : s.getOpenSessions()) {
    session.getBasicRemote().sendText(m);
   }
}

and here it is explained. https://blogs.oracle.com/PavelBucek/entry/optimized_websocket_broadcast.