What is WebSocket? — Full-Duplex Web Communication Explained
Definition
WebSocket is a communication protocol that provides full-duplex, bidirectional communication channels over a single TCP connection. Unlike HTTP, where the client must initiate every request and wait for the server to respond, WebSocket allows the server to push data to the client at any time without the client polling. This makes WebSockets ideal for real-time applications like chat, live updates, collaborative editing, and multiplayer games.
How It Works
WebSocket begins as an HTTP request with special Upgrade headers. The server responds with 101 Switching Protocols, and the connection is upgraded from HTTP to the WebSocket protocol. From this point, both client and server can send messages (frames) independently and simultaneously over the same TCP connection without HTTP overhead. Each WebSocket frame has a small header (2–10 bytes) compared to the hundreds of bytes of HTTP headers per request. WebSocket connections stay open until either party closes them or the network drops.
Common Use Cases
- ▸Real-time chat applications where messages must be delivered instantly to all participants
- ▸Live dashboards displaying constantly updating metrics or stock prices
- ▸Collaborative document editing (like Google Docs) where changes sync in real time
- ▸Multiplayer browser games requiring low-latency bidirectional state synchronization
- ▸Live sports scores, notification systems, and status pages
Example
// Client-side WebSocket:
const ws = new WebSocket("wss://chat.example.com/ws");
ws.onopen = () => ws.send("Hello server!");
ws.onmessage = (e) => console.log("Received:", e.data);
ws.onclose = () => console.log("Disconnected");
// HTTP Upgrade headers:
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZQ==Related Tools
FAQ
- What is the difference between WebSocket and HTTP long polling?
- Long polling has the client make an HTTP request and the server holds the response open until data is available, then the client immediately makes another request. This works but adds latency and HTTP overhead per event. WebSocket maintains one persistent connection with minimal framing overhead.
- What is the difference between WebSocket and Server-Sent Events (SSE)?
- SSE is unidirectional — server to client only — over HTTP. WebSocket is bidirectional. SSE is simpler to implement, uses standard HTTP, and has automatic reconnection built in. Use SSE for server-push use cases (live feeds, notifications); use WebSocket when the client also sends frequent messages.
- How do WebSockets work through proxies and load balancers?
- WebSockets require proxy and load balancer support for the HTTP Upgrade mechanism. Modern reverse proxies (Nginx, Caddy) and load balancers (AWS ALB) support WebSocket proxying. The load balancer must use sticky sessions (or the WebSocket must be handled by a dedicated server) because the connection is stateful.