Explain Codes LogoExplain Codes Logo

Closing WebSocket correctly (HTML5, Javascript)

javascript
websocket
javascript-best-practices
web-development
Anton ShumikhinbyAnton Shumikhin·Nov 9, 2024
TLDR

To properly shut down a WebSocket, apply the WebSocket.close() method:

// 'ws' is your WebSocket hat (fun!) if (ws.readyState === WebSocket.OPEN) { // Abracadabra. We're closing the show! ws.close(1000, 'Closing Time'); } // Handling closure situation ws.onclose = function() { // Much clean-up. Very memory. So effiency. Wow! (Dogecoin anyone?) ws.onclose = ws.onerror = ws.onopen = ws.onmessage = null; };

Probe readyState that it's open before closing and clear all callbacks to prevent any drama (memory issues).

Familiarizing WebSocket Protocol

Understanding WebSocket protocol is essential for a clean disconnection. When closing, send a control frame back to the client to acknowledge the termination. This feels like shaking hands before leaving a meeting.

Older versions used 0xFF and 0x00 bytes, the Ampex code. But, those days are gone. Now, we high-five modernity with a close frame (0x88).

Brace for Unexpected

What's life without some unexpected adventures, right? Keep a check on beforeunload or unload events. See below:

window.addEventListener('beforeunload', function() { if (ws.readyState === WebSocket.OPEN) { // May the close be with you! (ws.onclose = Force. Get it?) ws.onclose = function () {}; // Uber for WebSockets, anyone? "Browser, your ride is closing" ws.close(1000, 'Browser closing'); } });

Don't be that annoying friend who calls immediately after hanging up. Wait before you reconnect.

Prevention is Better than Cure

Nobody likes singing to a closed curtain. So, let’s prevent closing an already closed WebSocket:

if (ws.readyState === WebSocket.CLOSING || ws.readyState === WebSocket.CLOSED) { console.log("The WebSocket is already closing or closed, mate!"); } else { ws.close(1000, "Closing connection with style"); }

Server-side, Oh My!

Server side coding is where it gets real. Keep an eye on both onClose and onError events, like a hawk!

For Java EE users, javax.websocket.Endpoint is your best friend.

You Better Watch Out

Be the Sherlock of your code! Monitor WebSocket states using console.log and stay informed of all state transitions.

To avoid premature excitement (or handshakes), check readiness of WebSocket and the state of your application before establishing a connection.

Dealing with Browser Eccentricities

Browsers vary in handling WebSocket disconnections. You know, just like people, they are unique! Prepare for the good, bad and the ugly:

window.onbeforeunload = function() { if (ws && ws.readyState === WebSocket.OPEN) { ws.close(1000, "Bye Felicia!"); } };

Delays and Reconnections

Expect the unexpected! Even TCP socket closure might give you a hard time with delays. You might need an immediate reconnection sometimes. So, stay alert!