What is WebSocket? How It Works and When to Use It
WebSocket is a communication protocol that provides full-duplex (bidirectional) communication channels over a single TCP connection. It was standardised in 2011 and has become the foundation for real-time web applications — from chat and live dashboards to collaborative editing and multiplayer gaming. Understanding how WebSocket works helps you decide when it's the right tool and how to use it securely.
The Problem with HTTP Polling
HTTP is a request/response protocol: the client sends a request, the server sends a response, and the connection closes. This model works perfectly for loading web pages, but it's poorly suited for real-time data because the server can't push data to the client unless the client asks first.
Developers historically worked around this with polling: the client sends a request every few seconds to check for new data. This is simple but wasteful — most requests return an empty "no new data" response, and latency is bounded by the polling interval.
Long polling improved this: the client sends a request, and the server holds the connection open until new data is available, then responds. The client immediately sends a new request to wait for the next event. This reduces latency but still has overhead from repeatedly establishing connections.
How WebSocket Works
WebSocket starts with an HTTP request (the handshake) and then upgrades the connection to the WebSocket protocol. Once upgraded, the connection stays open and both the client and server can send messages at any time without the overhead of HTTP headers on each message.
WebSocket messages are framed — small binary frames rather than full HTTP requests. A text message frame has just 2–10 bytes of overhead. This makes WebSocket highly efficient for high-frequency message exchanges.
The connection remains open until either side closes it with a close frame, or the TCP connection drops. Most implementations add heartbeat ping/pong frames to detect dead connections.
The WebSocket Handshake
The WebSocket handshake is an HTTP Upgrade request. The client sends a standard HTTP GET request with special headers:
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
The server responds with HTTP 101 Switching Protocols:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
After this exchange, the connection is no longer HTTP — both sides communicate using the WebSocket frame format over the existing TCP connection.
WebSocket vs HTTP: Key Differences
- Connection — HTTP: new connection per request (or reused with keep-alive in HTTP/1.1, multiplexed in HTTP/2). WebSocket: single persistent connection.
- Communication direction — HTTP: client initiates, server responds. WebSocket: either side can send at any time.
- Overhead — HTTP: headers on every request (~500 bytes). WebSocket: 2–10 bytes per frame after handshake.
- Latency — HTTP: request-response round trip for each interaction. WebSocket: no round trip needed; server can push instantly.
Use ws:// for unencrypted connections and wss:// for TLS-encrypted connections (analogous to http:// and https://). Always use wss:// in production.
Common Use Cases
- Real-time chat — messages are pushed to all connected clients instantly without polling.
- Live dashboards — stock tickers, server monitoring, sports scores, analytics in real time.
- Collaborative editing — Google Docs-style shared editing where multiple users see each other's changes instantly.
- Multiplayer gaming — game state synchronisation between players with minimal latency.
- Notifications — push notifications to the browser (order updates, chat messages, alerts).
- IoT dashboards — sensor data streams from devices to a browser-based monitoring interface.
WebSocket vs Server-Sent Events
Server-Sent Events (SSE) is a simpler alternative for one-directional streaming from server to client. It uses a regular HTTP connection that the server keeps open, sending events as a text stream. SSE is easier to implement, automatically reconnects on disconnect, and works through HTTP/2 multiplexing.
Choose SSE when you only need server-to-client streaming (live feeds, progress updates). Choose WebSocket when you need bidirectional communication (chat, collaborative apps, games). SSE doesn't work over HTTP/1.1 in all browsers with many concurrent connections because of per-domain connection limits.
Security Considerations
Always use wss:// (WebSocket over TLS) in production — ws:// sends data in plaintext and is vulnerable to interception. Validate the Origin header on WebSocket upgrade requests to prevent cross-site WebSocket hijacking (CSWSH) — an attacker's page can open a WebSocket to your server using the victim's credentials if you don't check the origin. Implement authentication (JWT or session token in the first message or URL parameter) and rate limiting on your WebSocket handlers.
Test a WebSocket Connection Live
The WebSocket Tester at Tools.Fun lets you connect to any WebSocket endpoint, send messages, and see the responses in real time — without writing a single line of code. It's invaluable for debugging WebSocket APIs and testing server behaviour during development.
← Back