Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reliable WebSocket connection state detection

I've been looking around to implement a reliable WebSocket connection recovery mechanism.

After some investigation, I've found that one way is sending hearbeats to the server (ping/pong), and check if I receive the whole pong in a limited time.

Thus, either if the connection is actually down or it's very slow it would be considered disconnected if a pong wait timeouts, and code should call WebSocket.close().

At the end of the day, I'm asking this question to validate the connection-reconnection workflow using WebSockets, and check if I'm missing something.

That is, my question is, is this the right and reliable workflow to implement WebSockets reconnection mechanism?

like image 602
Matías Fidemraizer Avatar asked Jul 07 '14 08:07

Matías Fidemraizer


People also ask

How do I check my WebSocket connection 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.

Are WebSocket connections reliable?

It is worth to mention that WebSockets give us only an illusion of reliability. Unfortunately, the Internet connection itself is not reliable. There are many places when the connection is slow, devices often go offline, and in fact, there is still a need to be backed by a reliable messaging system.


1 Answers

The websocket protocol define special control frames for ping and pong, but they are not accessible through the JavaScript API. But if the server send those frames, the browser will answer.

However, if the connection is cut suddenly and become an half-open connection, although the server will detect it, the browser won't. So I guess that sending your own pings at application level is not a bad idea.

Answering your question yes, it is good idea because if the connection gets half opened, your client is not getting updates because he thinks it is connected. In websocket, the client has to initiate the connection, so even if the browser realizes the disconnection, there is nothing it can do to reconnect.

like image 190
vtortola Avatar answered Oct 16 '22 13:10

vtortola