-
-
Save sahat/8364120 to your computer and use it in GitHub Desktop.
var socket = io.connect('http://localhost'); | |
var startTime; | |
setInterval(function() { | |
startTime = Date.now(); | |
socket.emit('ping'); | |
}, 2000); | |
socket.on('pong', function() { | |
latency = Date.now() - startTime; | |
console.log(latency); | |
}); |
io.sockets.on('connection', function (socket) { | |
socket.on('ping', function() { | |
socket.emit('pong'); | |
}); | |
}); |
Also he didn't put a "var" before latency.
@flower1024 @steel-finger sounds like you two don't know what a callback is. very dangerous !
Can be kind enough to put an example here that isn't "very dangerous"?
@jpattisoninc Foxhunt's example isn't dangerous.
// Client
socket.emit('latency', Date.now(), function(startTime) {
var latency = Date.now() - startTime;
console.log(latency);
});
// Server
socket.on('latency', function (startTime, cb) {
cb(startTime);
});
While it looks magical that the server can "call" cb()
, calling cb()
on the server really just sends a message back to the client telling it to execute its callback with some given arguments.
It's more clear if you try console.log(cb.toString())
on the server.
Is this is milliseconds? Thanks!
ping and pong events are already used by socket.io for heartbeats so it is not advisable to create custom ping/pong events (name them something different). socket.io will send ping/pong messages (heartbeats) automatically and you can control the frequency with the connection options object (I believe default is 20 sec).
Hi @ForgeableSum, so how can we use Socket.io builtin ping/pong to calculate latency ? i didn't found any documentation about that.
Not sure about the code:
I would: