Read first — Due to repeated questions why this is supposed to work, let me clarify a bit.
- The client callback function is executed on the client, which is why it has access to the closure, including the startvariable containing the time stamp. This is the ack() argument in socket.io.
- The server naturally cannot call an arbitrary function on the client and access the function’s closure. But socket.ioallows 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!):
- Client stores current timestamp 1453213686429instart
- Client sends a pingevent to the server and is waiting for an answer
- Server responds to the ping event with “Please call your callback with empty arguments”
- Client receives the response and calls clientCallbackwith empty arguments (Check the demo code if you want to see arguments)
- clientCallbackagain takes the current timestamp on the client, e.g.- 1453213686449, and knows that- 20 mshave 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:
Client
var start = Date.now();
this.socket.emit( 'ping', function clientCallback() {
    console.log( 'Websocket RTT: ' + (Date.now() - start) + ' ms' );
} );
Server
socket.on( 'ping', function ( fn ) {
    fn(); // Simply execute the callback on the client
} );
Demo Code
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