Introduction to WebSockets
WebSockets provide full-duplex communication channels over a single TCP connection, enabling real-time data exchange between client and server.
Setting Up WebSocket Server
// server.js
const express = require('express');
const http = require('http');
const { WebSocketServer } = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocketServer({ server });
wss.on('connection', (ws) => {
console.log('Client connected');
// Send welcome message
ws.send(JSON.stringify({
type: 'welcome',
message: 'Connected to WebSocket server'
}));
// Handle incoming messages
ws.on('message', (message) => {
const data = JSON.parse(message);
console.log('Received:', data);
// Broadcast to all clients
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
type: 'broadcast',
data: data
}));
}
});
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
server.listen(3000, () => {
console.log('WebSocket server running on port 3000');
});
Client Implementation
// client.js (Browser)
const ws = new WebSocket('ws://localhost:3000');
ws.onopen = () => {
console.log('Connected to server');
ws.send(JSON.stringify({
type: 'message',
content: 'Hello from client'
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Received:', data);
if (data.type === 'broadcast') {
// Update UI with new data
updateUI(data.data);
}
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
ws.onclose = () => {
console.log('Disconnected from server');
};
Use Cases
- Chat Applications: Real-time messaging
- Live Updates: Stock prices, sports scores
- Collaboration: Real-time document editing
- Gaming: Multiplayer game state sync
- Notifications: Push notifications
Scaling WebSockets
For production, consider:
- Using Redis for pub/sub across multiple servers
- Load balancing with sticky sessions
- Implementing reconnection logic
- Using Socket.io for easier WebSocket management