Skip to content

Instantly share code, notes, and snippets.

@BonsaiDen
Created March 21, 2013 23:37
Show Gist options
  • Select an option

  • Save BonsaiDen/5217815 to your computer and use it in GitHub Desktop.

Select an option

Save BonsaiDen/5217815 to your computer and use it in GitHub Desktop.

Asynchronous Ping Measurement

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 PING to the client.

Server Implementation

  • on connection

    1. Save the current time as the clockOrigin
    2. Calculate a initial timeStamp via syncTimeStamp(now)
    3. Send a PING with [timeStamp, 0, 0]
  • on PONG (serverTS, clientTS, clientToServerRT)

    1. Calculate a timeStamp via syncTimeStamp(now)
    2. Calculate serverToClientRT via syncDiff(timeStamp, serverTS) + (serverTS - clientTS)
    3. Send a PONG with [timeStamp, clientTS, serverToClientRT]

Client Implementation

  • on connection

    1. Save the current time as the clockOrigin
  • on PING (serverTS, clientTS, serverToClientRT)

    1. Calculate a timeStamp via syncTimeStamp(now)
    2. Calculate clientToServerRT roundtrip via syncDiff(timeStamp, clientTS) + (clientTS - serverTS)
    3. Send a PONG with [serverTS, timeStamp, clientToServerRT]

Timestamps

Calculating a sync timestamp

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()); // 24356

Calculating the timestamp difference

In 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment