How can I find the response time (latency) of a client in NodeJS with sockets (socket.io)?

后端 未结 6 978
故里飘歌
故里飘歌 2021-01-30 07:11

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

6条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 08:09

    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 start variable 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.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!):

    1. Client stores current timestamp 1453213686429 in start
    2. Client sends a ping event to the server and is waiting for an answer
    3. Server responds to the ping event with “Please call your callback with empty arguments”
    4. Client receives the response and calls clientCallback with empty arguments (Check the demo code if you want to see arguments)
    5. 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:

    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

提交回复
热议问题