Skip to content

Measuring WebSockets connection latency

Val edited this page Jan 20, 2016 · 3 revisions

If the WebSocket implementation fulfill the contract IWebSocketLatencyMeasure, it exposes a Latency property that tells the latency of the last ping. WebSocketFactoryRfc6455 fulfills this contract.

Latency is measured using the ping/pong frames. Each ping frame contains a timestamp and the latency will be the half of the difference between that timestamp and the time when the pong arrives.

You can for example, get the current latency after each read.

IWebSocketLatencyMeasure l = webSocket as IWebSocketLatencyMeasure;
while (webSocket.IsConnected)
{
   String msg = await ws.ReadStringAsync(token).ConfigureAwait(false);
   ProcessMessage(msg);
   if(l != null)
       ReportLatency(l.Latency);
}

Or you can just have a independent thread to check the current latency of each thread.

Latency measurement depends on the Ping functionality, if you disable the ping, the latency will be 0.

PingMode must be set to PingModes.LatencyControl in order to this to work. If you choose to use PingModes.BandwidthControl, this feature won't work.