WebSockets
Create truly interactive applications with WebSockets - enabling full-duplex communication between client and server in real-time.
What are WebSockets?
WebSockets keep a persistent, two-way connection open between the browser and a server, so either side can send messages at any time with very low overhead. They're used for chat, live collaboration, multiplayer games and live dashboards. Open one with new WebSocket("wss://…") and use send() and the message event.
const ws = new WebSocket("wss://example.com/chat");
ws.addEventListener("open", () => ws.send(JSON.stringify({ type: "join" })));
ws.addEventListener("message", (e) => console.log(JSON.parse(e.data)));
ws.addEventListener("close", () => {/* reconnect with backoff */});Key Features
Bidirectional
Two-way communication channel
Real-time
Instant message exchange
Low Latency
Minimal communication overhead
Interactive WebSockets Demo
Experience real-time bidirectional communication with chat rooms, collaborative drawing, and multiplayer games - all powered by WebSockets.
WebSocket Protocol Architecture
Connection Lifecycle
- Handshake: HTTP upgrade to WebSocket
- Open: Full-duplex communication begins
- Data Exchange: Bidirectional messages
- Close: Graceful connection termination
- Error: Handle connection failures
Key Features
- Bidirectional: Client ↔ Server communication
- Low Latency: No HTTP overhead after handshake
- Binary Support: Text and binary data
- Cross-Origin: CORS support built-in
- Extensions: Compression, authentication
WebSocket API Implementation
Establishing Connection
Basic Connection
const socket = new WebSocket('ws://localhost:8080');
socket.onopen = (event) => {
console.log('Connected to WebSocket');
socket.send('Hello Server!');
};
socket.onmessage = (event) => {
console.log('Received:', event.data);
};
socket.onclose = (event) => {
console.log('Connection closed');
};
socket.onerror = (error) => {
console.error('WebSocket error:', error);
};Secure Connection (WSS)
const socket = new WebSocket('wss://api.example.com/ws', [
'chat',
'superchat'
]);
// Check protocol
console.log('Protocol:', socket.protocol);
// Ready states
console.log('State:', socket.readyState);
// CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3Data Transmission
Sending Data
// Text data
socket.send('Hello World!');
// JSON data
socket.send(JSON.stringify({
type: 'message',
content: 'Hello',
timestamp: Date.now()
}));
// Binary data
const buffer = new ArrayBuffer(8);
socket.send(buffer);
// Blob data
const blob = new Blob(['Hello'], { type: 'text/plain' });
socket.send(blob);Receiving Data
socket.onmessage = (event) => {
// Check data type
if (typeof event.data === 'string') {
try {
const message = JSON.parse(event.data);
handleMessage(message);
} catch (e) {
handleText(event.data);
}
} else if (event.data instanceof ArrayBuffer) {
handleBinaryData(event.data);
} else if (event.data instanceof Blob) {
event.data.text().then(handleText);
}
};Advanced Connection Management
Robust WebSocket manager with reconnection logic:
class WebSocketManager {
constructor(url, protocols = []) {
this.url = url;
this.protocols = protocols;
this.socket = null;
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 5;
this.reconnectDelay = 1000;
this.messageQueue = [];
this.isIntentionallyClosed = false;
}
connect() {
try {
this.socket = new WebSocket(this.url, this.protocols);
this.setupEventListeners();
} catch (error) {
console.error('Failed to create WebSocket:', error);
this.scheduleReconnect();
}
}
setupEventListeners() {
this.socket.onopen = (event) => {
console.log('WebSocket connected');
this.reconnectAttempts = 0;
this.flushMessageQueue();
this.onOpen?.(event);
};
this.socket.onmessage = (event) => {
this.onMessage?.(event);
};
this.socket.onclose = (event) => {
console.log('WebSocket closed:', event.code, event.reason);
if (!this.isIntentionallyClosed && this.shouldReconnect(event.code)) {
this.scheduleReconnect();
}
this.onClose?.(event);
};
this.socket.onerror = (error) => {
console.error('WebSocket error:', error);
this.onError?.(error);
};
}
send(data) {
if (this.socket?.readyState === WebSocket.OPEN) {
this.socket.send(data);
} else {
this.messageQueue.push(data);
}
}
close(code = 1000, reason = '') {
this.isIntentionallyClosed = true;
this.socket?.close(code, reason);
}
scheduleReconnect() {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
setTimeout(() => {
this.reconnectAttempts++;
console.log(`Reconnecting... attempt ${this.reconnectAttempts}`);
this.connect();
}, this.reconnectDelay * Math.pow(2, this.reconnectAttempts));
}
}
shouldReconnect(code) {
// Don't reconnect for certain close codes
return ![1000, 1001, 1005, 1006].includes(code);
}
flushMessageQueue() {
while (this.messageQueue.length > 0) {
this.send(this.messageQueue.shift());
}
}
}Real-time Application Patterns
Chat & Messaging Systems
Message Protocol
// Message structure
const message = {
type: 'chat_message',
id: generateId(),
sender: 'user123',
content: 'Hello everyone!',
timestamp: Date.now(),
room: 'general'
};
socket.send(JSON.stringify(message));Message Handling
socket.onmessage = (event) => {
const message = JSON.parse(event.data);
switch (message.type) {
case 'chat_message':
displayMessage(message);
break;
case 'user_joined':
handleUserJoined(message);
break;
case 'user_left':
handleUserLeft(message);
break;
case 'typing_start':
showTypingIndicator(message.sender);
break;
}
};Gaming & Collaborative Applications
Real-time state synchronization:
// Game state updates
const gameUpdate = {
type: 'game_state',
player: 'player1',
action: 'move',
position: { x: 100, y: 200 },
timestamp: performance.now(),
sequence: gameSequence++
};
// Optimistic updates
updateLocalGameState(gameUpdate);
socket.send(JSON.stringify(gameUpdate));
// Handle server reconciliation
socket.onmessage = (event) => {
const serverUpdate = JSON.parse(event.data);
if (serverUpdate.type === 'state_correction') {
reconcileGameState(serverUpdate);
} else if (serverUpdate.type === 'game_state') {
applyServerUpdate(serverUpdate);
}
};Live Data & Document Collaboration
Operational Transform
// Document operation
const operation = {
type: 'text_insert',
position: 42,
text: 'Hello',
author: 'user123',
version: documentVersion
};
// Apply operation locally
applyOperation(operation);
// Send to server
socket.send(JSON.stringify(operation));Conflict Resolution
socket.onmessage = (event) => {
const remoteOp = JSON.parse(event.data);
if (remoteOp.version < localVersion) {
// Transform remote operation
const transformed = transformOperation(
remoteOp,
pendingOperations
);
applyOperation(transformed);
}
};Server-Side WebSocket Implementation
Node.js with ws Library
Basic WebSocket server setup:
const WebSocket = require('ws');
const http = require('http');
const server = http.createServer();
const wss = new WebSocket.Server({ server });
// Store connected clients
const clients = new Map();
wss.on('connection', (ws, request) => {
const clientId = generateClientId();
clients.set(clientId, { ws, id: clientId });
console.log(`Client ${clientId} connected`);
// Send welcome message
ws.send(JSON.stringify({
type: 'welcome',
clientId: clientId,
message: 'Connected to WebSocket server'
}));
ws.on('message', (data) => {
try {
const message = JSON.parse(data);
handleMessage(clientId, message);
} catch (error) {
console.error('Invalid message:', error);
}
});
ws.on('close', (code, reason) => {
console.log(`Client ${clientId} disconnected`);
clients.delete(clientId);
broadcastUserLeft(clientId);
});
ws.on('error', (error) => {
console.error(`Client ${clientId} error:`, error);
});
});
function handleMessage(senderId, message) {
switch (message.type) {
case 'chat_message':
broadcastToRoom(message.room, {
...message,
sender: senderId,
timestamp: Date.now()
});
break;
case 'join_room':
joinRoom(senderId, message.room);
break;
case 'ping':
sendToClient(senderId, { type: 'pong' });
break;
}
}
function broadcastToRoom(room, message) {
clients.forEach((client) => {
if (client.room === room && client.ws.readyState === WebSocket.OPEN) {
client.ws.send(JSON.stringify(message));
}
});
}
server.listen(8080, () => {
console.log('WebSocket server listening on port 8080');
});Advanced Server Features
Authentication
wss.on('connection', (ws, request) => {
// Extract token from query params
const url = new URL(request.url, 'http://localhost');
const token = url.searchParams.get('token');
// Verify token
try {
const user = verifyToken(token);
ws.user = user;
} catch (error) {
ws.close(1008, 'Invalid token');
return;
}
// Continue with authenticated connection
});Rate Limiting
const rateLimiter = new Map();
ws.on('message', (data) => {
const clientId = getClientId(ws);
const now = Date.now();
const limit = rateLimiter.get(clientId) || { count: 0, resetTime: now + 60000 };
if (now > limit.resetTime) {
limit.count = 0;
limit.resetTime = now + 60000;
}
if (limit.count >= 100) { // 100 messages per minute
ws.send(JSON.stringify({ error: 'Rate limit exceeded' }));
return;
}
limit.count++;
rateLimiter.set(clientId, limit);
// Process message
handleMessage(data);
});Performance Optimization & Best Practices
Client-Side Optimization
- • Implement message queuing for offline scenarios
- • Use binary protocols for high-frequency updates
- • Implement client-side prediction for gaming
- • Batch small messages to reduce overhead
- • Use compression for large payloads
- • Implement heartbeat for connection monitoring
Error Handling Patterns
- • Exponential backoff for reconnection
- • Circuit breaker pattern for server issues
- • Graceful degradation to polling
- • Proper close code handling
- • Connection state management
Server-Side Optimization
- • Use clustering for horizontal scaling
- • Implement Redis pub/sub for multi-server
- • Monitor connection counts and memory
- • Use connection pooling
- • Implement proper backpressure handling
- • Optimize broadcast algorithms
Security Best Practices
- • Always use WSS in production
- • Validate all incoming messages
- • Implement proper authentication
- • Rate limit connections and messages
- • Monitor for DoS attacks
When to Use WebSockets vs Alternatives
Perfect for WebSockets
- • Real-time chat applications
- • Multiplayer games
- • Collaborative editing
- • Live trading platforms
- • IoT device communication
Consider Server-Sent Events
- • Live feeds (news, sports)
- • Server notifications
- • Progress updates
- • Stock price feeds
- • System monitoring
Stick with HTTP/REST
- • Traditional CRUD operations
- • File uploads/downloads
- • Authentication flows
- • SEO-important content
- • Simple request/response
Code Editor
<input id="msg" placeholder="Type a message" value="Hello!">
<button id="send">Send</button>
<ul id="log"></ul>Preview
WebSockets — step by step
Open a WebSocket connection
Create a WebSocket with new WebSocket('wss://example.com/socket'). Use wss:// for secure connections (same as HTTPS). The connection opens asynchronously and fires the open event when ready.
🎯 Quick Check
Which WebSocket event fires when the connection is successfully established?
WebSockets: summary
Key points
- Use
wss://(encrypted) in production, just as you'd use HTTPS. - Connections drop, so implement reconnection with exponential backoff.
- For one-way server-to-client updates, Server-Sent Events are simpler.
Frequently asked questions
›What is the difference between WebSockets and HTTP?
HTTP is request–response: the client asks and the server answers. A WebSocket stays open, and both sides can push messages whenever they want.
›Should I use WebSockets or Server-Sent Events?
Use SSE when only the server pushes updates, such as notifications or live scores. Use WebSockets when the client also sends frequent messages, such as chat or games.