Matías Fidemraizer
Matías Fidemraizer

Reputation: 64923

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?

Upvotes: 7

Views: 2987

Answers (1)

vtortola
vtortola

Reputation: 35905

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.

Upvotes: 4

Related Questions