WebSocket
WebSocket is a protocol that provides a persistent, full-duplex communication channel between client and server over a single TCP connection.
HTTP vs WebSocket
text
HTTP (request-response):
Client: GET /messages -->
<-- Server: [messages]
Client: GET /messages -->
<-- Server: [messages] (polling)
WebSocket (persistent):
Client: WS upgrade -->
<-- Server: connection established
<-- Server: new message! (pushed)
<-- Server: new message! (pushed)
Client: send message -->Setup
ts
// client
const ws = new WebSocket('wss://api.example.com/ws');
ws.onopen = () => {
console.log('Connected');
ws.send(JSON.stringify({ type: 'subscribe', channel: 'prices' }));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
updateUI(data);
};
ws.onclose = () => console.log('Disconnected');
ws.onerror = (err) => console.error(err);ts
// server (Node.js + ws library)
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws) => {
ws.on('message', (data) => {
const msg = JSON.parse(data.toString());
// broadcast to all clients
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ type: 'message', ...msg }));
}
});
});
});When to use WebSocket vs alternatives
| Use case | Solution |
|---|---|
| Chat, multiplayer game | WebSocket - bidirectional |
| Live notifications, feed | SSE (Server-Sent Events) - server to client only, simpler |
| Occasional updates | Polling - simplest, acceptable latency |
| File upload progress | Neither - XMLHttpRequest upload.onprogress on the upload request itself |
| Streaming an AI response | SSE or a streamed fetch response |
In React
tsx
function useLivePrices(symbol: string) {
const [price, setPrice] = useState(null);
useEffect(() => {
const ws = new WebSocket(`wss://prices.example.com/${symbol}`);
ws.onmessage = (e) => setPrice(JSON.parse(e.data).price);
return () => ws.close(); // cleanup on unmount
}, [symbol]);
return price;
}Use WebSocket when you need real-time bidirectional communication. For server-to-client only (notifications, live feed) prefer SSE - it's simpler, works over HTTP, and auto-reconnects.
The longer version, with what WebSockets cost in production: When to Use WebSockets.
updated
did you know it?