Below is a simple description of how to implement a two way ping measuring which
calculates the values for both server -> client and client -> server,
as these can differ on asymmetric routes.
To work around clock differences, the system uses the date and time of the
initial connection as it's origin.
Each side will calculate their roundtrip to the respective remote, and will then transmit it to them in order to create a shared state of the roundtrip time information.
In this model, it is assumed that the server will start the communication by sending the first
PINGto the client.
-
on connection
- Save the current time as the
clockOrigin - Calculate a initial
timeStampviasyncTimeStamp(now) - Send a
PINGwith[timeStamp, 0, 0]
- Save the current time as the
-
on PONG (serverTS, clientTS, clientToServerRT)
- Calculate a
timeStampviasyncTimeStamp(now) - Calculate
serverToClientRTviasyncDiff(timeStamp, serverTS) + (serverTS - clientTS) - Send a
PONGwith[timeStamp, clientTS, serverToClientRT]
- Calculate a
-
on connection
- Save the current time as the
clockOrigin
- Save the current time as the
-
on PING (serverTS, clientTS, serverToClientRT)
- Calculate a
timeStampviasyncTimeStamp(now) - Calculate
clientToServerRTroundtrip viasyncDiff(timeStamp, clientTS) + (clientTS - serverTS) - Send a
PONGwith[serverTS, timeStamp, clientToServerRT]
- Calculate a
In order to save network traffic, we can limit the range of the synchronizitation to 100000ms. In other words, we simply drop everything decimal place above a one-hundred-thousand.
function syncTimeStamp(now) {
now = now - clockOrigin; // subtract the clock origin
return now - (now / 100000| 0) * 100000; // Returns a number in the range of 0-99999
}
ts = syncTimeStamp(Date.now()); // 24356In order to calculate the absolute difference of two timeStamp's, we need to take care of wrap-around:
function syncDiff(now, last) {
if (now < last) {
return last - 100000;
}
return now - last;
}
diff = syncDiff(syncTimeStamp(Date.now()), oldTimeStamp); // 35