WebSockets Introduction
Real-time bidirectional communication - how WebSockets work and when to use them.
4 min read
What are WebSockets?#
HTTP is request-response: client asks, server answers, connection closes.
WebSockets are different: connection stays open, both sides can send messages anytime.
HTTP (Request-Response):
Client ──► Request ──► Server
Client ◄── Response ◄── Server
(Connection closes)
WebSockets (Bidirectional):
Client ◄──────────────► Server
(Always connected)
(Either can send anytime)
When to Use WebSockets#
Use WebSockets For:#
- Chat applications - Messages in real-time
- Live notifications - Instant updates
- Collaborative editing - Google Docs-style
- Live dashboards - Real-time metrics
- Multiplayer games - Player positions, actions
- Live sports/stocks - Frequent data updates
Don't Use WebSockets For:#
- Static content - Regular HTTP is fine
- Occasional updates - Polling or SSE might be simpler
- One-way updates - Consider Server-Sent Events (SSE)
WebSocket Lifecycle#
javascript
// 1. Client initiates connection
const ws = new WebSocket('ws://localhost:3000');
// 2. Connection established
ws.onopen = () => {
console.log('Connected!');
ws.send('Hello server');
};
// 3. Messages flow both ways
ws.onmessage = (event) => {
console.log('Received:', event.data);
};
// 4. Connection closes
ws.onclose = () => {
console.log('Disconnected');
};
Options in Node.js#
| Library | Best For | Features |
|---|---|---|
| Socket.io | Most projects | Auto-reconnect, rooms, fallbacks |
| ws | Raw WebSockets | Lightweight, fast, no extras |
| µWebSockets.js | High performance | Extremely fast, C++ bindings |
| Primus | Abstraction | Multiple transport support |
Recommendation
Socket.io for most projects - it handles reconnection, rooms, and browser fallbacks automatically. Use ws if you need raw WebSockets without overhead.
WebSocket vs Alternatives#
| Method | Direction | Use Case |
|---|---|---|
| WebSocket | Bidirectional | Chat, games, collaboration |
| SSE (Server-Sent Events) | Server → Client | Notifications, live feeds |
| Long Polling | Simulated real-time | Legacy browser support |
| HTTP Polling | Request-response | Simple, infrequent updates |
Server-Sent Events (SSE)#
Simpler alternative for one-way server-to-client:
javascript
// Server
app.get('/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
// Send event every second
const interval = setInterval(() => {
res.write(`data: ${JSON.stringify({ time: new Date() })}\n\n`);
}, 1000);
req.on('close', () => clearInterval(interval));
});
// Client
const eventSource = new EventSource('/events');
eventSource.onmessage = (event) => {
console.log(JSON.parse(event.data));
};
Key Concepts#
1. Connection State#
javascript
// WebSocket states
WebSocket.CONNECTING // 0 - Connecting
WebSocket.OPEN // 1 - Ready to send/receive
WebSocket.CLOSING // 2 - Closing
WebSocket.CLOSED // 3 - Closed
2. Message Types#
javascript
// Text messages (most common)
ws.send('Hello');
ws.send(JSON.stringify({ type: 'chat', message: 'Hi' }));
// Binary messages
ws.send(new ArrayBuffer(8));
ws.send(new Blob(['data']));
3. Heartbeats (Keep-Alive)#
javascript
// Ping/pong to detect dead connections
setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.ping();
}
}, 30000);
ws.on('pong', () => {
// Connection is alive
});
Scaling WebSockets#
WebSockets are stateful - each connection is tied to a specific server:
Problem:
┌────────┐ ┌──────────┐
│ User A │────►│ Server 1 │ User A connected here
└────────┘ └──────────┘
┌────────┐ ┌──────────┐
│ User B │────►│ Server 2 │ User B connected here
└────────┘ └──────────┘
How does User A send message to User B?
They're on different servers!
Solutions:
- Redis Pub/Sub - Broadcast between servers
- Sticky sessions - Route same user to same server
- Dedicated WebSocket service - Separate from API servers
Key Takeaways#
- WebSockets = persistent connection - Both sides can send anytime
- Use for real-time - Chat, notifications, live data
- Socket.io for most cases - Handles complexity for you
- Consider SSE - Simpler for server-to-client only
- Plan for scale - Need pub/sub for multiple servers
Continue Learning
Ready to level up your skills?
Explore more guides and tutorials to deepen your understanding and become a better developer.