What Is WebSocket? Real-Time Communication Guide
Can your chat app show messages without refreshing? Can your dashboard stream live data? WebSocket creates a persistent, bidirectional channel between client and server.
What Is WebSocket?
WebSocket is a protocol that provides a persistent, full-duplex communication channel between client and server. Unlike HTTP, once connected, both sides can send data at any time.
HTTP vs WebSocket
HTTP (Polling):
Client ──"New messages?"──→ Server (every 3 seconds)
Client ←──"No"──────────── Server
Client ──"New messages?"──→ Server
Client ←──"Yes! Here it is"── Server
WebSocket:
Client ←→ Server (persistent connection)
Server ──"New message!"──→ Client (instant)
| Feature | HTTP Polling | WebSocket | |---------|-------------|-----------| | Connection | New each request | Persistent | | Direction | Client → Server | Bidirectional | | Latency | High (poll interval) | Very low | | Overhead | High (HTTP headers) | Low (frame header) |
How WebSocket Works
1. Handshake (HTTP Upgrade)
Client: GET /chat HTTP/1.1
Upgrade: websocket
Server: HTTP/1.1 101 Switching Protocols
Upgrade: websocket
2. Data Exchange
Both sides send data frames once connected.
Vanilla WebSocket
Server (Node.js)
const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws) => {
ws.on('message', (data) => {
const msg = JSON.parse(data);
wss.clients.forEach((client) => {
if (client.readyState === 1) {
client.send(JSON.stringify({
user: msg.user,
text: msg.text,
time: new Date().toISOString()
}));
}
});
});
});
Client (Browser)
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
ws.send(JSON.stringify({ user: 'Ali', text: 'Hello!' }));
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
console.log(`${msg.user}: ${msg.text}`);
};
Socket.IO
Socket.IO adds auto-reconnection, rooms, and fallback mechanisms on top of WebSocket.
Server
const { Server } = require('socket.io');
const io = new Server(3000);
io.on('connection', (socket) => {
socket.on('join-room', (room) => socket.join(room));
socket.on('chat-message', (data) => {
io.to(data.room).emit('new-message', {
user: data.user,
text: data.text,
time: new Date()
});
});
});
Client
import { io } from 'socket.io-client';
const socket = io('http://localhost:3000');
socket.emit('join-room', 'general');
socket.on('new-message', (msg) => addMessageToUI(msg));
Common Use Cases
| Use Case | Example | |----------|---------| | Chat | WhatsApp Web, Slack | | Notifications | GitHub, Twitter | | Live data | Stock prices, crypto | | Gaming | Multiplayer games | | Collaboration | Google Docs | | IoT | Sensor data streams |
WebSocket vs Alternatives
| Tech | Direction | Best For | |------|-----------|----------| | WebSocket | Bidirectional | Chat, gaming | | SSE | Server → Client | Notifications, feeds | | HTTP Polling | Client → Server | Simple updates |
Best Practices
- Heartbeat/ping — Detect dead connections
- Reconnection — Exponential backoff strategy
- Authentication — Validate tokens during handshake
- Rate limiting — Prevent message flooding
- Compression — Compress large payloads
- Horizontal scaling — Use Redis Pub/Sub for multi-server
Conclusion
WebSocket is the backbone of real-time applications. It's ideal for chat, notifications, live data, and multiplayer games. Use vanilla WebSocket for simple projects; Socket.IO for complex scenarios with rooms and reconnection.
Learn WebSocket and real-time apps on LabLudus.