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

FR6 picture FR6 · Nov 1, 2010 · Viewed 37k times · Source

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 a request take to come back to the client) between the client and the server?

My first idea was that the client #1 could send a timestamp with is request, so when client #2 will receive the action of the client #1 he will adjust is action speed to remove the delay of the request. But the problem is that maybe the system date time of the two clients are not identical so it is not possible two know the reel delay on the request of client #1.

The other solution was to use the timestamp of the server, but now how can I know the latency of a client?

Answer

kanaka picture kanaka · Nov 1, 2010

I'm going to assume you are using WebSockets or Socket.IO since you are implementing a game where latency matters (and you tagged it as such).

I would think the server should probably measure and keep track of this for each client.

You probably want to implement some sort of ping action that the server can request of the client. As soon as the client receives the request, it sends back a response to the server. The server then divides by 2 and updates the latency for that client. You probably want the server to do this periodically with each client and probably average the last several so that you don't get strange behavior from sudden but temporary spikes.

Then, when there is a message from one client that needs to be sent (or broadcast) to another client, the server can add client1's latency to client2's latency and communicate this as the latency offset to client2 as part of the message. client2 will then know that the event on client1 happened that many milliseconds ago.

An additional reason to do this on the server is that some browser Javascript timestamps are inaccurate: http://ejohn.org/blog/accuracy-of-javascript-time/. I suspect node.js timestamps are just as accurate (or more so) than V8 (which is one of the few accurate ones).