Question

I would like to broadcast a single message to every client every second (think about it as custom heartbeat mechanism).

So the NodeJS app is started, sockets are created and when I connect from the client app the heartbeat messages are broadcasted. I'm still developing the client application and that means hitting F5 all the time and reloading the application. The new client SocketIO connection is created on load and this results in heartbeat messages coming to client app with rate much higher than 1 message/sec.

There is nothing special about the code - server side:

var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8080);

io.sockets.on('connection', function(socket) {
  ...
  setInterval(function() {
    console.info('broadcasting heartbeat');
    socket.broadcast.emit('heartbeat', /* custom heartbeat*/);
  }, 1000);
  ...
});

Client side:

var socket = io.connect('localhost', { 'reconnect': false, port: 8080 });
socket.on('heartbeat', function(data) { console.log('heartbeat'); });

Can anybody give me some advice what's wrong? Thanks

Was it helpful?

Solution

No need to startup up an interval each time. You can store the intervalID, and even clear it out with clearInterval(INTERVAL); when it's not needed.

var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8080);

var INTERVAL;

io.sockets.on('connection', function(socket) {
  ...
  if (!INTERVAL) {
    INTERVAL = setInterval(function() {
      console.info('broadcasting heartbeat');
      socket.broadcast.emit('heartbeat', /* custom heartbeat*/);
    }, 1000);
  }
  ...
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top