2024-09-03
Master WebSocket protocol for bidirectional real-time communication in modern web applications.
WebSockets enable real-time, bidirectional communication between browsers and servers. This guide covers WebSocket fundamentals, implementation patterns, scaling strategies, and building production-ready real-time applications.
Client-side WebSocket implementation:
// Create WebSocket connection
const ws = new WebSocket('wss://example.com/socket');
// Connection opened
ws.addEventListener('open', (event) => {
console.log('Connected to server');
ws.send(JSON.stringify({ type: 'hello', data: 'Client connected' }));
});
// Listen for messages
ws.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
console.log('Message from server:', message);
});
// Handle errors
ws.addEventListener('error', (error) => {
console.error('WebSocket error:', error);
});
// Connection closed
ws.addEventListener('close', (event) => {
console.log('Disconnected from server');
// Implement reconnection logic here
});
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
const clients = new Set();
server.on('connection', (ws, req) => {
const clientId = generateId();
const client = { id: clientId, ws, isAlive: true };
clients.add(client);
console.log(`Client ${clientId} connected`);
ws.on('message', (data) => {
try {
const message = JSON.parse(data);
handleMessage(client, message);
} catch (error) {
console.error('Invalid message:', error);
}
});
ws.on('close', () => {
clients.delete(client);
console.log(`Client ${clientId} disconnected`);
});
ws.on('pong', () => {
client.isAlive = true;
});
});
// Heartbeat to detect broken connections
const interval = setInterval(() => {
clients.forEach((client) => {
if (!client.isAlive) {
clients.delete(client);
return client.ws.terminate();
}
client.isAlive = false;
client.ws.ping();
});
}, 30000);
Robust reconnection with exponential backoff:
class ReconnectingWebSocket {
constructor(url, options = {}) {
this.url = url;
this.reconnectDelay = options.reconnectDelay || 1000;
this.maxReconnectDelay = options.maxReconnectDelay || 30000;
this.reconnectDecay = options.reconnectDecay || 1.5;
this.reconnectAttempts = 0;
this.shouldReconnect = true;
this.connect();
}
connect() {
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
console.log('Connected');
this.reconnectAttempts = 0;
};
this.ws.onclose = () => {
if (this.shouldReconnect) {
const delay = Math.min(
this.reconnectDelay * Math.pow(this.reconnectDecay, this.reconnectAttempts),
this.maxReconnectDelay
);
console.log(`Reconnecting in ${delay}ms...`);
this.reconnectAttempts++;
setTimeout(() => this.connect(), delay);
}
};
}
send(data) {
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(data);
} else {
// Queue message or handle offline state
}
}
}
// Room-based messaging system
class RoomManager {
constructor() {
this.rooms = new Map();
}
joinRoom(roomId, client) {
if (!this.rooms.has(roomId)) {
this.rooms.set(roomId, new Set());
}
this.rooms.get(roomId).add(client);
}
leaveRoom(roomId, client) {
const room = this.rooms.get(roomId);
if (room) {
room.delete(client);
if (room.size === 0) {
this.rooms.delete(roomId);
}
}
}
broadcast(roomId, message, excludeClient = null) {
const room = this.rooms.get(roomId);
if (room) {
room.forEach(client => {
if (client !== excludeClient && client.ws.readyState === WebSocket.OPEN) {
client.ws.send(JSON.stringify(message));
}
});
}
}
}
Horizontal Scaling with Redis
Use Redis Pub/Sub to synchronize WebSocket servers across multiple instances.
Sticky Sessions
Configure load balancer to route WebSocket connections from same client to same server.
Message Queue Integration
Use message queues (RabbitMQ, Kafka) for reliable message delivery and processing.
🔒 Use WSS (WebSocket Secure) for encrypted connections
🔑 Implement authentication before establishing WebSocket connection
⚡ Rate limiting to prevent spam and DoS attacks
✅ Input validation for all incoming messages
🎯 Origin checking to prevent CSRF attacks
💾 Message size limits to prevent memory exhaustion
Published on 2024-09-03 • Category: Web Development
← Back to BlogFree online developer tools and utilities for encoding, formatting, generating, and analyzing data. No registration required - all tools work directly in your browser.
Built for developers, by developers. Privacy-focused and open source.
Free online tools for Base64 encoding, JSON formatting, URL encoding, hash generation, UUID creation, QR codes, JWT decoding, timestamp conversion, regex testing, and more.
© 2024 NarvikHub. All rights reserved.