I\'m trying to create a multiplayer game with NodeJS and I want to synchronize the action between clients.
What would be the best way to find the latency (the time that
After socket.io connection has been established, you create a new Date object on the client, let's call it startTime. This is your initial time before making a request to the server. You then emit a ping event from the client. Naming convention is totally up to you. Meanwhile server should be listening for a ping event, and when it receives the ping, it immediately emits a pong event. Client then catches the pong event. At this time you want to create another date object that represents Date.now(). So at this point you have two date objects - initial date before making a request to the server, and another date object after you make a request to the server and it replied. Subtract the startTime from current time and you have the latency.
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 available as a Github Gist.