WebSocket Fundamentals Deep Dive
Understand the WebSocket protocol, handshake, framing, and how it differs from HTTP polling.
What you'll learn
- WebSocket protocol handshake and upgrade
- Frame format: text, binary, ping/pong, close
- WebSocket vs HTTP long-polling vs SSE
- Connection lifecycle and state machine
Concept
WebSocket Fundamentals Deep Dive
WebSocket provides full-duplex communication over a single TCP connection, keeping it open for real-time data flow.
The Handshake
A WebSocket connection starts as an HTTP GET with Upgrade headers. The server responds 101 Switching Protocols. After handshake, the same TCP connection carries bidirectional frames.
Frame Format
Messages are sent as frames with opcodes: 0x1 text, 0x2 binary, 0x8 close, 0x9 ping, 0xA pong. Frames can be fragmented. Ping/pong serve as heartbeats.
WebSocket vs Alternatives
HTTP long-polling has high overhead. SSE is server-to-client only. WebSocket is bidirectional with low overhead after handshake, ideal for chat and gaming.
Connection Lifecycle
States: CONNECTING(0), OPEN(1), CLOSING(2), CLOSED(3). onopen fires after handshake, onmessage on data, close() triggers onclose with code and reason.
Example
const ws = new WebSocket('wss://echo.websocket.org');
ws.onopen = () => { ws.send(JSON.stringify({type:'greeting',text:'Hello'})); };
ws.onmessage = (e) => console.log('Received:', JSON.parse(e.data));
ws.onclose = (e) => console.log(`Closed: ${e.code}`);
setTimeout(() => ws.close(1000, 'Normal'), 5000);
The WebSocket client connects, sends JSON on open, logs messages, and closes after 5 seconds. Close codes: 1000 normal, 1006 abnormal.
Try it
- JSON Formatter
WebSocket messages are often JSON - format and validate them.
Common mistakes
The mistake
Not handling reconnection after disconnect.
The fix
Implement exponential backoff reconnection. Listen to onclose and reconnect if not intentional.
The mistake
Sending data before connection is open.
The fix
WebSocket send() throws if not OPEN. Wait for onopen or queue messages.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.