HTML 5 - Close Web Sockets in a Browser

As the server knows about closing the Web Socket connection in HTML5 in the following scenarios and in other cases.

  • The browser is closed suddenly
  • Updating the browser (creating a new socket connection or will still use the existing connection)
  • System shutdown
+4
source share
3 answers

If the client shuts down without the ability to notify the server, the main characteristics of the TCP implementation determine the behavior.

As long as your application (and the host system itself) does not try to send any data on this broken connection, the host will not understand that something is wrong. Consequently, a connection can remain β€œopen” for a long time and allocate resources from a server perspective.

However, the moment the data was tried to be sent to the remote end, the remote end will not confirm the retrieval, and TCP retransmission comes into play. It includes a certain number of repetitions and uses timeouts. The exact parameters are implementation dependent (operating system used). When the final relay fails, the TCP connection closes and resources are freed on the server side. So you can

  • rely on the fact that at some point your application might want to write the missing remote end and at the same time start detecting a dead connection, or
  • detect a missing remote end using something like pings at the application level or
  • use something like pings at the operating system level using keepalive TCP methods.
+1
source

The easiest part of your question is the browser update part. IE, FF, and Chrome will close the open connection and open a new one. I think any other browser will do the same.

I can only guess points 1 and 3: if the client can still close the tcp connection, the server will immediately know that the connection has been closed. If you are using tomcat, the onClose method of the MessageInbound instance is called.

If the client could not close the tcp connection, the server will wait for some timeout. The server, of course, quickly overheats when it tries to write something to the socket. To do this, you can implement a heart rate mechanism. Websockets seems to have the ability to auto-beat, but not all browsers and servers seem to support it.

0
source

If a user closes a browser tab with an open web socket, the server will not know that it was closed immediately. However, as Jan-Philip says, if you try to record an operation, it will fail using an error if you know the current state of the connection.

For example, when using ws lib for nodejs, if you try to send data to a closed websocket, an exception will be thrown, for example, [Error: not open]. You know them, that the connection no longer exists, and you can perform any cleaning.

0
source

All Articles