1

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

4

1 回答 1

3

无需每次启动间隔。clearInterval(INTERVAL);您可以存储 intervalID,甚至在不需要时将其清除。

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);
  }
  ...
});
于 2013-03-26T21:44:24.463 回答