Working with WebSockets
1. Creating WebSocket Server
Example: ws library
import { WebSocketServer } from "ws";
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", (ws) => {
ws.on("message", (msg) => ws.send(`echo: ${msg}`));
});
| Library | Use |
|---|---|
ws | Most popular, low-level |
uWebSockets.js | High performance |
| Built-in client v22+ | WebSocket global |
2. Handling WebSocket Connections
| Event | Fires |
|---|---|
connection | Client connected |
headers | Customize handshake response |
upgrade | Manual handling |
error | Server error |
3. Sending Messages (ws.send)
| Payload | Frame Type |
|---|---|
| String | Text frame |
| Buffer / TypedArray | Binary frame |
{ binary: true } | Force binary |
| Callback / Promise | Get send completion |
4. Receiving Messages
5. Broadcasting to All Clients
Example
function broadcast(data) {
for (const client of wss.clients) {
if (client.readyState === client.OPEN) client.send(data);
}
}
6. Implementing Heartbeat/Ping-Pong
Example: Detect dead clients
function noop() {}
function alive() { this.isAlive = true; }
wss.on("connection", (ws) => {
ws.isAlive = true;
ws.on("pong", alive);
});
const interval = setInterval(() => {
for (const ws of wss.clients) {
if (!ws.isAlive) return ws.terminate();
ws.isAlive = false;
ws.ping(noop);
}
}, 30_000);
7. Handling Connection Close
| Event | Fires |
|---|---|
close | Normal close |
| Codes | 1000 normal, 1001 going away, 1006 abnormal |
| Methods | ws.close(code, reason) / ws.terminate() |
8. Handling WebSocket Errors
| Source | Mitigation |
|---|---|
| Network drop | Reconnect with exponential backoff |
| Frame parse error | Library auto-closes |
| Slow consumer | Check ws.bufferedAmount |
9. Implementing WebSocket Authentication
| Strategy | How |
|---|---|
| Token in query string | wss://x/?token=... |
| Cookie | Browser auto-sends; verify in upgrade handler |
| Subprotocol header | Sec-WebSocket-Protocol for token |
| First-message auth | Validate then upgrade state |
10. Using Socket.io for Real-Time Communication
| Feature | Use |
|---|---|
| Auto-reconnect | Built in |
| Rooms / namespaces | Pub/Sub patterns |
| Acknowledgements | Per-event callbacks |
| Adapter (Redis) | Multi-node scaling |
| Fallbacks | HTTP long polling |