javascriptnode.jswebsocketws

When is it preferable to use ws.terminate() VS ws.close()


I know terminate hard closes a socket not letting it hang or send more packets like close does, and terminate sends a different code when closing a socket (1006 vs close sending 1000). So this raises the question, why would I even used ws.close() when I dont plan on reopening a socket? Ive seen so many examples that just use ws.close() and never reopen it. Is it just not well known or standard or is there something behind the scenes Im not aware of?


Solution

  • The downside of having a closing handshake in the protocol is that a closing connection might be left hanging in a limbo state when the other end is no longer responding at all. Only a timeout will end that, with various problems.

    Why would I even use ws.close() when I don't plan on reopening a socket?

    You should always gracefully close() your web socket to notify the other end that the connection ends. You should also send the close reason 1000 (as the client) or 1001 (as the server) to tell the other end that they should not try to reconnect.

    If a server needs to drop the connection but will become available again soon after, it might forcibly close the TCP connection. This will cause the client to immediately detect an abnormal closure, and it might attempt to automatically reconnect after a short time. (There is no method to do this in the ws library, you'd have to call ws._socket.end()).

    If you terminate() a working connection, the other end will not notice anything. Only when it tries to send something (e.g. a ping()), after some timeout it will find that the tcp connection was lost and the websocket will become abnormally closed. Don't do that!

    You should only ever call terminate() if you have determined that the connection has already been lost - like in the heartbeat example. This will free up resources on your end quickly and immediately fire the respective stream events on the ws object.