🔌 WebSockets = Real-time Communication
HTTP polling is inefficient. WebSockets enable real-time, bidirectional communication between client and server.
📝 WebSocket Basics
// Client Setup
const socket = new WebSocket('wss://api.example.com/ws');
// Connection Events
socket.onopen = function() {
console.log('WebSocket connected');
socket.send(JSON.stringify({
type: 'subscribe',
channel: 'updates'
}));
};
socket.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log('Received:', data);
updateUI(data);
};
socket.onerror = function(error) {
console.error('WebSocket error:', error);
};
socket.onclose = function() {
console.log('WebSocket disconnected');
reconnect();
};
// Sending Messages
function sendMessage(message) {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(message));
} else {
console.warn('Socket not ready');
}
}
// Reconnection Logic
function reconnect() {
setTimeout(() => {
const newSocket = new WebSocket('wss://api.example.com/ws');
// Re-establish connection
}, 3000);
}
🎯 Real-time Applications
// Chat Application
class ChatApp {
constructor() {
this.socket = new WebSocket('wss://chat.example.com');
this.messageContainer = document.getElementById('messages');
this.init();
}
init() {
this.socket.onmessage = (event) => {
const message = JSON.parse(event.data);
this.displayMessage(message);
};
}
sendMessage(text) {
this.socket.send(JSON.stringify({
type: 'message',
text: text,
timestamp: Date.now()
}));
}
displayMessage(message) {
const div = document.createElement('div');
div.textContent = `${message.user}: ${message.text}`;
this.messageContainer.appendChild(div);
}
}
// Live Dashboard
class Dashboard {
constructor() {
this.socket = new WebSocket('wss://metrics.example.com');
this.charts = {};
this.init();
}
init() {
this.socket.onmessage = (event) => {
const data = JSON.parse(event.data);
this.updateMetrics(data);
};
}
updateMetrics(data) {
// Update real-time charts
Object.entries(data).forEach(([key, value]) => {
if (this.charts[key]) {
this.charts[key].update(value);
}
});
}
}
// Error Handling with Exponential Backoff
class ResilientWebSocket {
constructor(url) {
this.url = url;
this.retryDelay = 1000;
this.maxDelay = 30000;
this.connect();
}
connect() {
this.socket = new WebSocket(this.url);
this.socket.onclose = () => {
console.log('Reconnecting...');
setTimeout(() => this.connect(), this.retryDelay);
this.retryDelay = Math.min(this.retryDelay * 2, this.maxDelay);
};
}
}
💡 WebSocket Best Practices
- Always implement reconnection logic
- Use heartbeat/ping messages
- Validate incoming messages
- Implement message queuing
- Handle connection closure gracefully
WebSockets power the real-time web. From chat to live analytics, they enable instant communication.
