Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the latency time for a one way trip from client to server

I was wondering if there was a way to get the time (in ms) between the client sending a message to the server and the server receiving that message

I cannot compare the time in milliseconds with the server and client using Date.now() because every device might be off by a few seconds.

I can find the time for a two way trip, logging the time when I send a message and logging the time again when I receive a message in return from the server. However, The time it takes for a message to get from the client to the server may not be the same as it is for the message to get from the server to the client on a two way trip. So I cant just simply divide this time by 2.

Any suggestions on how I can find this time or at least the difference between Date.now() on the client and the server?

Thanks in advance.

like image 744
wilson wilson Avatar asked Nov 08 '22 05:11

wilson wilson


1 Answers

You can achieve this if you first synchronize the clocks of both your server and client using NTP. This requires access to an external server, however you can configure NTP to be installed on your server as well (see ntpd)

There are several modules that implement NTP in node: node-ntp-client or sntp

Here's an example with node-ntp-client:

var ntpClient = require('ntp-client');

var clientOffset = 0;

ntpClient.getNetworkTime("pool.ntp.org", 123, function(err, date) {
    if(err) {
        console.error(err);
        return;
    }

    clientOffset = Date.now() - date;
});

When sending data to the server, send the timestamp as well:

var clientTimestamp = Date.now() - clientOffset 

Server would have its own offset. When receiving the package, it can calculate latency using:

var latency = Date.now() - serverOffset - clientTimestamp;
like image 134
mihai Avatar answered Nov 10 '22 00:11

mihai