Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the Ping of a WebSocket Connection?

small question. How can I calculate the ping of a WebSocket connection? The server is set up using Node.js and node-websocket-server, if that matters at all.

like image 630
Alexander Avatar asked May 01 '11 18:05

Alexander


People also ask

Can you ping a WebSocket?

Pings and Pongs: The Heartbeat of WebSockets At any point after the handshake, either the client or the server can choose to send a ping to the other party.

Is WebSocket low latency?

WebSocket is a protocol for creating a fast two-way channel between a web browser and a server that overcomes the limitations of HTTP, offering low latency communications between a user and a web service.

How do I check my WebSocket status?

You can check if a WebSocket is connected by doing either of the following: Specifying a function to the WebSocket. onopen event handler property, or; Using addEventListener to listen to the open event.


1 Answers

There is few ways. One that is offered by Raynos - is wrong. Because client time and server time are different, and you cannot compare them.

Solution with sending timestamp is good, but it has one issue. If server logic does some decisions and calculations based on ping, then sending timestamp, gives risk that client software or MITM will modify timestamp, that way it will give another results to server.

Much better way, is sending packet to client with unique ID, that is not increment number, but randomized. And then server will expecting from client "PONG" message with this ID. Size of ID should be same, I recommend 32bits (int). That way server sends "PING" with unique ID and store timestamp of the moment message sent, and then waiting until it will receive response "PONG" with same ID from Client, and will calculate latency of round-trip based on stored timestamp and new one on the moment of receiving PONG message. Don't forget to implement case with timeout, to prevent lost PING/PONG packet stop the process of checking latency.

As well WebSockets has special packet opcode called PING, but example from post above is not using this feature. Read this official document that describes this specific opcode, it might be helpful if you are implementing your own WebSockets protocol on server side: https://www.rfc-editor.org/rfc/rfc6455#page-37

like image 68
moka Avatar answered Sep 20 '22 02:09

moka