Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

SocketIO broadcasting too fast

SocketIO broadcasting too fast

Problem

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

Problem courtesy of: Karel Frajták

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);
  }
  ...
});
Solution courtesy of: generalhenry

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

SocketIO broadcasting too fast

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×