Skip to content Skip to sidebar Skip to footer

Can I Broadcast To All Websocket Clients

I'm assuming this isn't possible, but wanted to ask in case it is. If I want to provide a status information web page, I want to use WebSockets to push the data from the server to

Solution 1:

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

Solution 2:

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);
    });
  });
});

Solution 3:

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:

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

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

Solution 4:

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

In Java,

@OnMessagepublicvoidonMessage(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.

Solution 5:

It depends on the server-side really. Here's an example of how it's done using Tomcat7:

Tomcat 7 Chat Websockets Servlet Example

and an explanation of the how it's constructed here.

Post a Comment for "Can I Broadcast To All Websocket Clients"