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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With