WebSockets & WebRTC
22 min read
WebSocketWebRTCReal-timeBi-directionalSignalingSTUN/TURN
Real-Time Communication on the Web
HTTP is a request-response protocol — the client always initiates. But what about live chat, multiplayer games, or video calls? That's where WebSockets and WebRTC come in.
WebSockets
WebSockets provide a persistent, bi-directional connection between client and server over a single TCP connection.
How It Works:
- HTTP Upgrade: The connection starts as a normal HTTP request with an
Upgrade: websocketheader. - Handshake: Server responds with
101 Switching Protocols. - Full-Duplex: Both sides can now send messages at any time without HTTP overhead.
When to Use WebSockets:
- Chat applications
- Live dashboards & stock tickers
- Collaborative editing (Google Docs-style)
- Multiplayer games
- Real-time notifications
WebRTC (Web Real-Time Communication)
WebRTC enables peer-to-peer audio, video, and data communication directly between browsers — no server relay needed for the media stream itself.
The Signaling Process:
- Offer/Answer: Peers exchange SDP (Session Description Protocol) messages via a signaling server.
- ICE Candidates: STUN servers help peers discover their public IP. If direct connection fails, TURN servers relay traffic.
- P2P Connection: Once established, media flows directly between browsers.
WebSocket vs. SSE vs. Polling
| Method | Direction | Connection | Best For |
|---|---|---|---|
| Long Polling | Server → Client | New connection each time | Legacy compatibility |
| SSE (Server-Sent Events) | Server → Client only | Persistent | Live feeds, notifications |
| WebSocket | Bi-directional | Persistent | Chat, games, collaboration |
| WebRTC | Peer-to-Peer | Direct | Video/audio calls |