π 1. The Problem Before WebSockets
- Traditional web apps used HTTP (request/response).
- Limitation: Client must request, server only responds.
-
If client wants updates (e.g., new chat message), it must poll (keep asking the server: βAny new data?β).
- β Wastes bandwidth.
- β Slow (depends on polling interval).
- β Doesnβt scale well.
π 2. What is WebSocket?
- WebSocket = a full-duplex, bidirectional communication channel between client and server over a single TCP connection.
-
Unlike HTTP:
- HTTP: Request β Response β Close (stateless).
- WebSocket: Persistent connection stays open until explicitly closed.
Think of it like a telephone call (both sides can talk anytime) vs. postal letters (client sends, waits for server reply).
βοΈ 3. How WebSockets Work (Step by Step)
(A) Connection Establishment (Handshake)
-
Client sends an HTTP request with an
Upgradeheader:GET /chat HTTP/1.1 Host: example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Version: 13β This is a WebSocket handshake.
-
Server responds with 101 Switching Protocols if it agrees:
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=β Now, the HTTP connection is upgraded to a WebSocket.
(B) Communication Phase
-
After handshake:
- Client and server exchange frames (lightweight data packets).
- Frames can carry text, binary, or control messages.
- Both sides can send messages at any time (full-duplex).
(C) Closing the Connection
- Either side can send a
Closeframe. - TCP connection is closed gracefully.
π‘ 4. Where Do We Use WebSockets?
β Real-time chat apps (WhatsApp Web, Slack) β Live sports scores / stock tickers β Collaborative apps (Google Docs, Figma) β Online gaming (real-time updates, player positions) β IoT / telemetry streaming (device continuously pushing data) β Live dashboards / monitoring systems (e.g., server logs, analytics)
π 5. Technical Details
Protocol:
- Runs over TCP (usually port 80 for ws:// or 443 for wss://).
- WSS = WebSocket Secure (encrypted with TLS, like HTTPS).
Efficiency:
- WebSockets avoid HTTP overhead (no repeated headers).
- Use a single persistent connection for thousands of messages.
Scaling:
- Requires load balancers / proxies that support connection persistence.
- Popular backend support: Node.js, Spring Boot, Django Channels, Go, etc.
Browser Support:
-
All modern browsers support WebSockets via:
const socket = new WebSocket("wss://example.com/socket"); socket.onopen = () => console.log("Connected!"); socket.onmessage = (event) => console.log("Message:", event.data); socket.send("Hello Server!");
π 6. Alternatives & Comparisons
Polling
- Client keeps asking server β inefficient.
Long Polling
- Client requests β server holds connection until data available β then responds.
- Better than polling, but still creates overhead.
Server-Sent Events (SSE)
- Server β Client (one-way, not bidirectional).
- Lighter than WebSockets for just push notifications.
WebSocket
- Two-way, real-time.
- Best when both client and server need to talk frequently.
π 7. Example Flow: Chat Application
- User opens app β WebSocket handshake with chat server.
- Connection established β stays open.
- User sends a message β
socket.send("Hello"). - Server receives it β broadcasts via WebSocket to other connected clients.
- Other clients receive instantly via
onmessage. - Connection closes when user logs out or disconnects.
β In short:
- WebSockets = persistent, bidirectional communication over TCP.
- Used for real-time apps (chat, gaming, dashboards, collaboration).
- Starts with HTTP handshake, upgrades to WebSocket protocol, then exchanges lightweight frames.
- Much more efficient than polling or long polling.