3
votes

When establishing a web socket connection between client to server the connection can close unexpectedly for several reasons:

  1. Inactivity on the TCP channel.
  2. server issue which makes the connection to close.
  3. Client crash or reload/ refresh.

I am looking for the way of dealing with such situations or, at least, know they occurred.

When reading about WebSocket close, I understood the WebSocket protocol support server initiated pings pongs which can be used for the server to know if a client has crashed. (client initiated ping pong are not supported). - is it the best way to deal with client crash?

Also, I see in spec that on the client side we can listen to the onClose event and that there are several codes to understand why connection has been closed - When the server crashed is that onClose event is always called?

1

1 Answers

5
votes

Both server and clients can send pings, however there is no method in the Javascript API to send such control frames.

A common approach is to send protocol level pings from the server to client regularly. If the server does not get a pong frame in a given time, the server disconnects the client.

However, clients should also know if the server is unreachable or the connection is half open, so having an application level ping/pong (i.e.: some user data representing a ping or pong) would allow both server and client figure out if the other end is not reachable anymore. As before, the server can send pings and expect pongs in a given time, but also the client can expect to have pings in a given time or consider itself disconnected, and then try to reconnect again.

About closing reasons, worth to check : getting the reason why websockets closed

If the server crashes and the connection remains half open, you will have to detect this situation yourself and call .close() on the WebSocket object, and then the onclose event will be called.