Table of Contents
WebSocket is a protocol that lets a browser and server send messages to each other over one open connection. Either side can send without waiting for the other to make a new request. That makes it useful for features such as live chat, multiplayer games, and collaborative editing.

How a WebSocket connection works
- Connect: JavaScript opens a URL starting with
ws://orwss://. Usewss://for TLS-protected connections. - Negotiate: In the HTTP/1.1 handshake, the browser asks to upgrade the connection and the server replies with
101 Switching Protocolsif it agrees. The browser validates the response. Your app normally leaves that work to its client and server libraries. - Exchange messages: Once connected, both sides can send text or binary data. To send JSON, serialize it to text and validate the parsed message on receipt.
- Close: Either side can initiate a closing handshake. An outage can also cut the connection, so the client needs to handle an unexpected close.

What the handshake looks like
These examples show the HTTP/1.1 upgrade. The browser’s Sec-WebSocket-Key and server’s Sec-WebSocket-Accept are part of the handshake. They do not authenticate the user.


WebSocket, polling, or Server-Sent Events?
- Polling: Use ordinary HTTP requests at intervals when updates are infrequent and a short delay is fine.
- Server-Sent Events: Use SSE when the server pushes updates and the browser can send its own occasional requests separately. Examples include a status feed or job progress.
- WebSocket: Use it when both sides send frequent messages or when many small two-way updates make repeated requests cumbersome.

What to handle in the browser
The browser API exposes open, message, error, and close events. Wait for WebSocket.OPEN before calling send(). Watch bufferedAmount for data your app has queued but the network hasn’t sent yet. If messages arrive faster than you can process them, the standard browser API won’t slow the sender automatically.
What to test before shipping
Test idle timeouts at the proxy, network changes, and server restarts. Reconnect with a delay that grows after repeated failures, then rejoin subscriptions or request fresh state as needed. On the server, verify expected origins for browser connections, authenticate the session, check authorization for actions, and limit message size and rate. TLS protects the connection, while these checks govern what each caller can do.
Reader Comments 0
Sign in with email or Google to join the discussion.