Skip to content

Instantly share code, notes, and snippets.

@sahat
Last active February 23, 2022 17:09
Show Gist options
  • Save sahat/8364120 to your computer and use it in GitHub Desktop.
Save sahat/8364120 to your computer and use it in GitHub Desktop.
Calculate client-server latency using socket.io
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');
});
});
@tcaer
Copy link

tcaer commented May 10, 2017

Is this is milliseconds? Thanks!

@ForgeableSum
Copy link

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).

@aRandomKiwi
Copy link

Hi @ForgeableSum, so how can we use Socket.io builtin ping/pong to calculate latency ? i didn't found any documentation about that.

@NeXTs
Copy link

NeXTs commented Sep 25, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment