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}`));
});
LibraryUse
wsMost popular, low-level
uWebSockets.jsHigh performance
Built-in client v22+WebSocket global

2. Handling WebSocket Connections

EventFires
connectionClient connected
headersCustomize handshake response
upgradeManual handling
errorServer error

3. Sending Messages (ws.send)

PayloadFrame Type
StringText frame
Buffer / TypedArrayBinary frame
{ binary: true }Force binary
Callback / PromiseGet send completion

4. Receiving Messages

Example

ws.on("message", (data, isBinary) => {
  const msg = isBinary ? data : data.toString();
});

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

EventFires
closeNormal close
Codes1000 normal, 1001 going away, 1006 abnormal
Methodsws.close(code, reason) / ws.terminate()

8. Handling WebSocket Errors

SourceMitigation
Network dropReconnect with exponential backoff
Frame parse errorLibrary auto-closes
Slow consumerCheck ws.bufferedAmount

9. Implementing WebSocket Authentication

StrategyHow
Token in query stringwss://x/?token=...
CookieBrowser auto-sends; verify in upgrade handler
Subprotocol headerSec-WebSocket-Protocol for token
First-message authValidate then upgrade state

10. Using Socket.io for Real-Time Communication

FeatureUse
Auto-reconnectBuilt in
Rooms / namespacesPub/Sub patterns
AcknowledgementsPer-event callbacks
Adapter (Redis)Multi-node scaling
FallbacksHTTP long polling