WebSockets
Real-time bidirectional communication with new WebSocket(), onmessage, and send()
Skills taught: api.websocket-connect, api.websocket-send, api.websocket-events, api.reconnect-logic
Real-time communication with WebSockets
// ── Basic WebSocket connection ──
const ws = new WebSocket('wss://api.example.com/chat');
ws.onopen = () => {
console.log('Connected');
// Send a JSON message
ws.send(JSON.stringify({
type: 'auth',
token: sessionStorage.getItem('token'),
}));
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
switch (msg.type) {
case 'chat': renderMessage(msg.data); break;
case 'presence': updateOnlineUsers(msg.data); break;
case 'typing': showTypingIndicator(msg.data); break;
case 'error': console.error(msg.message); break;
}
};
ws.onerror = (error) => console.error('WebSocket error:', error);
ws.onclose = (event) => {
console.log(`Closed: code=${event.code} reason=${event.reason}`);
// 1000 = normal close, 1001 = going away, 1006 = abnormal (reconnect)
if (event.code !== 1000) reconnect();
};
// Send a chat message
function sendMessage(text) {
if (ws.readyState !== WebSocket.OPEN) return;
ws.send(JSON.stringify({ type: 'chat', text, timestamp: Date.now() }));
}
// ── Auto-reconnect with exponential backoff ──
let reconnectDelay = 1000;
function reconnect() {
console.log(`Reconnecting in ${reconnectDelay / 1000}s...`);
setTimeout(() => {
const newWs = new WebSocket('wss://api.example.com/chat');
// re-attach event handlers...
reconnectDelay = Math.min(reconnectDelay * 2, 30_000); // cap at 30s
}, reconnectDelay);
}
// ── Heartbeat — keep connection alive through proxies ──
const heartbeat = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'ping' }));
}
}, 30_000);
// Clean up on close
ws.addEventListener('close', () => clearInterval(heartbeat));
Tip: Always implement reconnect logic. WebSockets close unexpectedly — network hiccups, server deploys, idle timeouts. Use exponential backoff (1s, 2s, 4s...) with a cap (~30s) to avoid hammering a struggling server.
Frequently Asked Questions
Should I use WebSocket or Server-Sent Events (SSE)?
If your app only needs the SERVER to push updates to the client (live notifications, news feeds, price tickers), SSE is simpler: `const source = new EventSource('/events')`. SSE uses plain HTTP, reconnects automatically, works over HTTP/2 multiplexing, and is easier to debug. If you need the CLIENT to also send messages to the server in real time (chat, collaborative editing, multiplayer games), use WebSocket. SSE is unidirectional; WebSocket is bidirectional.