WebSockets
Real-time bi-directional communication and handshake process
What are WebSockets?
Real-time bi-directional communication for the modern web
WebSockets provide a persistent, full-duplex communication channel between a client and server over a single TCP connection. Unlike HTTP's request-response model, WebSockets allow both sides to send messages independently and simultaneously.
A WebSocket connection starts as a regular HTTP request with an
Upgrade: websocket header. Once the server agrees,
the protocol switches from HTTP to WebSocket, and both sides can exchange
lightweight frames with minimal overhead (as low as 2 bytes per frame).
The WebSocket Handshake
How an HTTP connection upgrades to WebSocket
WebSocket Opening Handshake
Watch the upgrade from HTTP to WebSocket protocol
Client sends a regular HTTP request with Upgrade: websocket header and a random Sec-WebSocket-Key
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZQ==
Sec-WebSocket-Version: 13Random base64-encoded value sent by client. Server hashes it with a GUID to prove it received the request.
Server's proof of understanding. Computed by concatenating the key with a magic GUID and taking the SHA-1 hash.
Bi-Directional Message Flow
Real-time data exchange between client and server
Live Message Stream
Watch messages flow between client and server in real-time
UTF-8 encoded text data (JSON, plain text)
Raw binary data (images, audio, files)
Keep-alive heartbeat frames
Graceful connection termination
Connection Lifecycle
WebSocket API events, ready states, and close codes
WebSocket Ready States
WebSocket Events
Creating a WebSocket Connection
// Create a new WebSocket connection
const ws = new WebSocket('wss://api.example.com/ws');
// Send data (only when readyState is OPEN)
ws.send(JSON.stringify({ type: 'chat', message: 'Hello!' }));
// Close the connection gracefully
ws.close(1000, 'Normal closure');Common Close Codes
WebSockets vs Alternatives
Choosing the right real-time communication approach
Real-Time Communication Approaches
Compare polling, long polling, SSE, and WebSockets
Connection Patterns
Common Use Cases
When WebSockets are the right tool for the job
When NOT to Use WebSockets
- • Simple CRUD: REST APIs are simpler and more appropriate
- • One-way server pushes: Server-Sent Events (SSE) are lighter
- • Infrequent updates: HTTP polling is simpler to implement
- • Request/response patterns: HTTP with caching is more efficient
Key Terms to Remember
Master these terms for technical interviews