How to handle connection closure in WebSockets

How to handle connection closure in WebSockets

WebSockets are a protocol that allows bidirectional communication between a client and a server over a single TCP communication. WebSockets are useful for applications that require real-time updates, such as chat, games, or life data feeds.

However, WebSockets also need to handle connection closure gracefully, as there are various scenarios where the connection can be terminated unexpectedly, such as network failures, server crashes, or client disconnection. This article will explore how to handle connection closure in WebSockets using JavaScript.

Detecting Connection Closure

The first step towards handling connection closure is to detect it when it happens. The WebSocket API provides an event called "close" that is fired when a connection with a Web/socket is closed. We can use the "addEventListener" method or the "onclose" property to register a handler for this event. For Example:

const ws = new WebSocket('ws://localhost:8080');

ws.addEventListener('close', (event) =>
{
console.log('The connection has been closed successfully.');
});

// or

ws.onclose = (event) => {
console.log('The connection has been closed successfully.');
};

The "close" event has some properties that can give us more information about the reason and the status of the closure:

  • code: An unsigned short containing the close code sent by the server or the client. The standard codes are defined in [RFC 6455] (https://tools.ietf.org/html/rfc6455#section-7.4), but custom codes can also be used.

  • reason: A string indicating the reason the server or the client closed the connection. This is specific to the server and sub-protocol.

  • wasClean: A boolean value that indicates whether the connection was cleanly closed or not. A clean closure means both parties agreed to terminate the connection and exchanged close frames.

We can access these properties in our handler function and perform different actions based on them. For example:

ws.onclose = (event) =>
{
console.log('The connection was closed with code ${event.code} and reason ${event.reason}');
if (event.wasClean)
{
console.log('The connection was closed cleanly.');
}
else
{
console.log('The connection was closed abruptly.');
//try to reconnect or notify the user
}
};

Initiating Connection Closure

Sometimes, we may want to close the WebSocket connection from our code, either from the client side or from the server side. To do this, we can use the "WebSocket.close()" method. This method takes two optional parameters: a close code and a close reason. For example:

// from the client side
ws.close(1000, 'Normal Closure'); //close with code 1000 and reason 'Normal Closure'

//from the server side (using Node.js and ws library)
ws.close(1001, 'Going away'); //close with code 1001 and reason 'Going Away'

The "WebSocket.close()" method initiates the closing handshake, which is a process where both parties exchange close frames and acknowledge each other's intention to close the connection. The closing handshake ensures that both parties have received all the messages that were sent before the closure and that no data is lost.

However, if the readyState of the WebSocket connection is already in the CLOSE state, then the method does nothing. Therefore, we should check the readyState before calling the method. The readyState can have one of the four values:

  • CONNECTING: The connection is being established

  • OPEN: The connection is established and communication is possible

  • CLOSING: The connection is going through the closing handshake

  • CLOSED: The connection has been closed or could not be opened

For example:

if (ws.readyState !== WebSocket.CLOSED)
{
ws.close(1000, 'Normal Closure');
}

Conclusion

In this article, we learned how to handle connection closure in WebSockets using JavaScript. We also learned how to detect when a connection is closed using the "close" event and its properties. We also learned how to initiate a connection closure using the "WebSocket.close()" method and its parameters. Finally, we learned about the closing handshake and the readyState of a WebSocket connection.

WebSockets are a powerful tool for creating real-time applications, but they also require careful handling of connection closure to avoid data loss and ensure user satisfaction. By following the best practices described in this article, we can create robust and reliable WebSocket applications.


Source:

  1. WebSocket: close event - Web APIs | MDN - MDN WebDocs.
    https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close_event

  2. How to Disconnect a WebSocket Connection in JavaScript?
    https://www.designcise.com/web/tutorial/how-to-disconnect-a-websocket-connection-in-javascript

  3. How to Close a WebSocket (Correctly) - Forty Years of Code.
    https://mcguirev10.com/2019/08/17/how-to-close-websocket-correctly.html

  4. Handling connection loss with WebSockets - Stack Overflow.
    https://stackoverflow.com/questions/26971026/handling-connection-loss-with-websockets


Image Courtesy:

  1. https://websockets.readthedocs.io/en/stable/topics/design.html

  2. https://www.pubnub.com/blog/websockets-alternatives/

  3. Bing AI Image Generator