Search code examples
node.jssocket.ioreal-time

Socket.IO only emitting to all clients


Right part of my code is

io.sockets.on('connection', function(socket){
var interval = setInterval(function() {
    repaintGraph()
    socket.emit('set data chart', '{"series":[['+series+']]}');
}, 1000 );

The chart in this case, if I have 3 users connected, the chart updates 3 times in one second I need to execute the code 1 time in 1 second, regardless of the number of clients


Solution

  • You can run the interval code outside of the connection code:

    setInterval(function() {
      repaintGraph();
      io.emit('set data chart', '{"series":[['+series+']]}');
    }, 1000);
    
    io.on('connection', function() {
      ...
    });
    

    io.emit() will broadcast the message to all connected clients, every second.

    There's a little bit of an inefficiency in the code, in that it will call repaintGraph() every second even if there aren't any clients connected, but it makes the code much easier.