Closing WebSocket correctly (HTML5, Javascript)
To properly shut down a WebSocket, apply the WebSocket.close()
method:
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:
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:
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:
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!
Was this article helpful?