WebSockets provide full‑duplex, low‑latency communication between the browser and a server over a single TCP connection. Unlike HTTP, which is request/response‑based, WebSockets keep the connection open, enabling real‑time data exchange for chats, live dashboards, multiplayer games, and more.
1. How WebSockets Work
-
Handshake – A client sends an HTTP
Upgrade
request to switch protocols. -
Upgrade – The server responds with
101 Switching Protocols
if it accepts. - Full‑Duplex Channel – Both sides can now send data frames at any time until the connection closes.
Client —— HTTP Upgrade ——> Server
Client <—— 101 Switching —— Server
Client ⇄⇄⇄ WebSocket Frames ⇄⇄⇄ Server
2. Creating a WebSocket in the Browser
const socket = new WebSocket('wss://echo.websocket.org');
socket.addEventListener('open', () => {
console.log('Connected');
socket.send('Hello WebSocket');
});
socket.addEventListener('message', event => {
console.log('Message from server:', event.data);
});
socket.addEventListener('close', () => console.log('Disconnected'));
-
ws://
– Unencrypted -
wss://
– Encrypted via TLS (recommended)
3. Building a Node.js WebSocket Server (ws Library)
npm i ws
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => {
ws.on('message', msg => ws.send(`Echo: ${msg}`));
});
4. Handling Binary Data
WebSockets support text and binary frames. Use ArrayBuffer
, Blob
, or TypedArray
.
socket.binaryType = 'arraybuffer';
socket.onmessage = e => {
const view = new Uint8Array(e.data);
// process binary data
};
5. Common Use Cases
- Chat & Collaboration (Slack‑like apps)
- Live Dashboards (financial tickers, IoT telemetry)
- Gaming (multiplayer state sync)
- Live Notifications & Feeds
6. Best Practices & Pitfalls
- Ping/Pong Heartbeats – Detect dead connections.
- Back‑pressure Handling – Monitor bufferedAmount to avoid memory bloat.
- Reconnect Logic – Exponential backoff when the socket closes unexpectedly.
- Authentication – Use tokens (e.g., JWT) during the handshake or subprotocols.
-
Security – Always prefer
wss://
; validate incoming frames on the server.
function connect() {
const ws = new WebSocket('wss://example.com');
let retry = 0;
ws.onclose = () => {
const delay = Math.min(1000 * 2 ** retry++, 16000);
setTimeout(connect, delay);
};
}
7. Alternatives & Comparisons
Feature | WebSocket | SSE (EventSource) | HTTP Polling |
---|---|---|---|
Direction | Bidirectional | Server→Client | Client→Server |
Binary Support | Yes | No | No |
Overhead | Low | Low | High |
Browser Support | Excellent | Good | Universal |
8. Conclusion
WebSockets enable efficient, real‑time communication across the web stack. Whether you’re building a chat app or streaming sensor data, mastering the WebSocket API and its best practices will help you deliver seamless live experiences.
Have you built with WebSockets? Share tips and stories below! 🚀