WebSockets enable full-duplex communication between clients and servers. Let's explore how to build real-time applications.
What are WebSockets?
WebSockets provide a persistent connection for real-time data transfer:
- Full-duplex: Both sides can send data simultaneously
- Low latency: No HTTP overhead after initial handshake
- Efficient: Single connection for multiple messages
WebSocket Protocol
The WebSocket handshake starts as HTTP:
Client → Server: GET /ws HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Server → Client: HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: UpgradeServer Implementation
typescript
import WebSocket from 'ws';
const wss = new WebSocket.Server({ port: 8080 });
const clients = new Set<WebSocket>();
wss.on('connection', (ws) => {
clients.add(ws);
ws.on('message', (data) => {
// Broadcast to all clients
clients.forEach(client => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
});
ws.on('close', () => {
clients.delete(ws);
});
});Client Implementation
typescript
class WebSocketClient {
private ws: WebSocket;
private reconnectAttempts = 0;
private maxReconnectAttempts = 5;
constructor(url: string) {
this.ws = new WebSocket(url);
this.setupEventHandlers();
}
private setupEventHandlers() {
this.ws.onopen = () => {
console.log('Connected');
this.reconnectAttempts = 0;
};
this.ws.onmessage = (event) => {
this.handleMessage(event.data);
};
this.ws.onclose = () => {
this.handleReconnect();
};
this.ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
}
private handleReconnect() {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++;
setTimeout(() => {
this.ws = new WebSocket(this.ws.url);
this.setupEventHandlers();
}, 1000 * this.reconnectAttempts);
}
}
send(data: any) {
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(data));
}
}
private handleMessage(data: string) {
const message = JSON.parse(data);
// Handle message
}
}Conclusion
WebSockets are perfect for real-time features like chat, notifications, and live updates.