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
Read first — Due to repeated questions why this is supposed to work, let me clarify a bit.
start
variable containing the time stamp. This is the ack() argument in socket.io.socket.io
allows to define a callback funtion, which appears to be executed by the server, but this actually just passes the function arguments through the web socket, and the client then calls the callback.What happens below (please do check the example code!):
1453213686429
in start
ping
event to the server and is waiting for an answerclientCallback
with empty arguments (Check the demo code if you want to see arguments)clientCallback
again takes the current timestamp on the client, e.g. 1453213686449
, and knows that 20 ms
have passed since it sent the request.Imagine the druid (client) holding a stopwatch and pushing the button when the messenger (event) starts running, and pushing it again when the messenger arrives with his scroll (function arguments). The druid then reads the scroll and adds the ingredient names to his potion recipe and brews the potion. (callback)
Okay, forget the previous paragraph, I guess you got the point.
Although the question has already been answered, here a short implementation for checking the RTT with socket.io
:
var start = Date.now();
this.socket.emit( 'ping', function clientCallback() {
console.log( 'Websocket RTT: ' + (Date.now() - start) + ' ms' );
} );
socket.on( 'ping', function ( fn ) {
fn(); // Simply execute the callback on the client
} );
Demo code as node module: socketIO-callback.tgz Set it up and run it with
npm install
node callback.js
and then navigate to http://localhost:5060