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

后端 未结 6 1048
故里飘歌
故里飘歌 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:11

    What I usually do to send timestamp with request:

    1. On the client, create a new Date() and send timestamp: date.getTime() to the server, with every JSON request.
    2. On the server, upon receiving a request, put a processed: (new Date()).getTime() in the object.
    3. Handle request.
    4. On the response, put the timestamp from the request, and a new processed field: processed: (new Date()).getTime() - req.processed that now contains the number of milliseconds it took to process the request.
    5. On the client, when receiving a response, take the timestamp (which is the same that was sent on pt 1) and subtract it from the current time, and subtract processing time (processed), and there is your "real" ping time in milliseconds.

    I think you should always include the time for both request and response in the ping time, even if there is one-way communication. This is because that is the standard meaning behind "ping time" and "latency". And if it is one-way communication and the latency is only half of the real ping time, that's just a "good thing".

提交回复
热议问题