In Socket.IO, is 'heartbeat' an event that can be used to trigger other actions?
Asked Answered
P

1

9

This exact code doesn't work, but, I was hoping something like it was:

io.sockets.on('connection', function(socket) {
    socket.on('heartbeat', function() {
        // Do something here...
    });
});

Is something like this possible? I mean, I know I can just make a different function that triggers every, say, 15 seconds using a setInterval:

io.sockets.on('connection', function(socket) {
    setInterval(function() {
        // Do something
    },15000);
});

But since the heartbeat is already running at this interval, why not make use of it?

In any case, any insight would be greatly appreciated.

Procambium answered 11/7, 2012 at 19:37 Comment(0)
T
9

I think that I see what you're trying to do. There are a few exposed events that you can check here - list of Socket.io events - but there is no "heartbeat" event that you can tap into to fire at a set interval.

You're on the right track with the second piece of code -

setInterval(function() {
    socket.emit('heartbeat', someData);
}, 5000);

And on the client side -

socket.on('heartbeat', function(data) {
    console.log(data);
})
Tetrachloride answered 12/7, 2012 at 1:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.