Dylan Turney
Dylan Turney

Reputation: 85

How to send Websocket messages with the least amount of latency?

I'm working on a Websocket server programmed in Node.js and I'm planning to send out a multicast message to upwards of 20,000 users. The message will be sent out on a regular interval of a second, however I am worried about the performance from the Node.js server.

I understand that Node.js works asynchronously and creates and destroys threads as it requires, but I am unsure of its efficiency. Ideally I would like to send out the message with an average latency of 5ms.

Currently I'm sending out messages to all users through running through a for loop of all the connected clients as following:

function StartBroadcastMessage()
{
  console.log("broadcasting socket data to client...!");

  for(var i=0;i < clientsWithEvents.length;i++){ //Runs through all the clients

      client = clientsWithEvents[i];
      if(client.eventid.toLowerCase() == serverEventName.toLowerCase()) //Checks to see if the Client Event names and server names are the same
        client.connection.sendUTF(GetEventSocketFeed(client.eventid)); //Sends out event data to that particular client
    }

  timeoutId = setTimeout(StartBroadcastMessage,2*1000);
}

Is this an efficient way of sending out a multicast message with a low latency, or is there a better way?

Also, is there an efficient way to perform a load test on the server simulating a number of devices connected to the Websocket server? (So far I have found this Node app https://github.com/qarea/websockets-stress-test)

Upvotes: 1

Views: 998

Answers (1)

shivakumar
shivakumar

Reputation: 3397

You can use socket.io to broad cast message.

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.broadcast.emit('user connected');
});

This will avoid latency(iterating all socket objects and formatting message) in sending individual message to client.

Upvotes: 1

Related Questions