mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
Every page now loads /webmcp.js, scripts/webmcp.ts with its types stripped (npm run webmcp). Where the browser has document.modelContext it registers two read-only tools: search_skills over the published skills index, and get_skill, which returns a skill's markdown checked against the index digest. The markdown alternate link moves from build.py to site.py, so CI holds every page to it. The API catalog gains the site itself (llms.txt and the skills index) and hanzo.ai/agents; the live discovery check now fetches every catalog link. tests/site.mjs drives the tools through a recording modelContext, and checks a browser without one loads clean.
842 lines
37 KiB
HTML
842 lines
37 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>realtime-websocket-implementation</title>
|
|
<meta name="color-scheme" content="dark">
|
|
<style>
|
|
/* Committed to one visual world: a dark instrument panel. No light variant —
|
|
the dot field and the hairline rules only read on black, and a naive
|
|
inversion would wash both out. Every colour is painted explicitly so the page
|
|
never borrows a host background. */
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
|
|
|
|
:root{
|
|
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
|
|
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
|
|
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
|
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
|
|
--font-zen-pixel-square:'Zen Pixel Square',monospace;
|
|
--mono:var(--font-zen-mono);
|
|
--sans:var(--font-zen-sans);
|
|
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
|
|
--r:999px; --r-soft:14px;
|
|
}
|
|
*{box-sizing:border-box}
|
|
html{-webkit-text-size-adjust:100%}
|
|
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
|
|
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
|
|
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
|
|
|
|
/* The dot field. A halftone made of one repeating radial-gradient, faded out
|
|
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
|
|
/* No overflow clip here: the dot field is inset to the box already, and a clip
|
|
would cut off the copy-prompt menu. */
|
|
.hero{position:relative;border-bottom:1px solid var(--line)}
|
|
.hero::before{content:"";position:absolute;inset:0;
|
|
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
|
|
background-size:7px 7px;
|
|
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
pointer-events:none}
|
|
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
|
|
|
|
nav{border-bottom:1px solid var(--line)}
|
|
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
|
|
justify-content:space-between;align-items:center;gap:1rem}
|
|
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--ink);text-decoration:none;
|
|
display:inline-flex;align-items:center;gap:.6rem}
|
|
.brand i{font-style:normal;color:var(--faint)}
|
|
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
|
|
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--soft);text-decoration:none}
|
|
nav a.up:hover{color:var(--ink)}
|
|
|
|
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
|
|
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
|
|
h1 em{font-style:normal;color:var(--faint)}
|
|
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
|
|
|
|
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
|
|
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
|
|
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
|
|
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
|
|
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
|
|
line-height:1.2;font-weight:400}
|
|
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
|
|
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
|
|
.btn.solid:hover{background:#d8d8d4}
|
|
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
|
|
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
|
|
|
|
/* Copy-prompt selector. Each row copies the prompt for its own target. */
|
|
.copy{position:relative;display:inline-flex}
|
|
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
|
|
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
|
|
padding:.4rem;display:flex;flex-direction:column;
|
|
box-shadow:0 12px 32px rgba(0,0,0,.75)}
|
|
.menu[hidden]{display:none}
|
|
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
|
|
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
|
|
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
|
|
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
|
|
white-space:nowrap}
|
|
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
|
|
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
|
|
.mi:hover .mark{color:var(--ink)}
|
|
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
|
|
letter-spacing:.1em;text-transform:uppercase}
|
|
|
|
/* Works-with bar: one scrolling row, name and mark per agent. */
|
|
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
|
|
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
|
|
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
|
|
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
|
|
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
|
|
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
|
|
display:flex;align-items:center}
|
|
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
|
|
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
|
|
-webkit-overflow-scrolling:touch;
|
|
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
|
|
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
|
|
.bar::-webkit-scrollbar{display:none}
|
|
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
|
|
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
|
|
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
|
|
text-decoration:none;background:var(--ground)}
|
|
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
|
|
.agent .mark{width:.95rem;height:.95rem}
|
|
|
|
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
|
|
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
|
|
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
|
|
p{margin:0 0 1rem;max-width:70ch}
|
|
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
|
|
li{margin:.22rem 0}
|
|
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
|
|
text-decoration-color:var(--line-hi)}
|
|
a:hover{text-decoration-color:var(--ink)}
|
|
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
|
|
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
|
|
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
|
|
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
|
|
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
|
|
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
|
|
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
|
|
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
|
|
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
|
|
display:block;overflow-x:auto}
|
|
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
|
|
|
|
.curl{display:block;background:var(--panel);border:1px solid var(--line);
|
|
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
|
|
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
|
|
white-space:pre;line-height:1.9}
|
|
.curl b{color:var(--ink);font-weight:400}
|
|
.curl i{font-style:normal;color:var(--faint)}
|
|
|
|
/* index */
|
|
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
|
|
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
|
|
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
|
|
#q:focus{outline:none;border-color:var(--soft)}
|
|
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
|
|
text-transform:uppercase;margin:0 0 2rem}
|
|
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
|
|
padding-bottom:.45rem}
|
|
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
|
|
border-radius:var(--r-soft);text-decoration:none}
|
|
.row:hover{background:#0a0a0a}
|
|
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
|
|
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
|
|
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
|
|
color:var(--faint);font-size:.85rem}
|
|
footer a{color:var(--soft)}
|
|
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
|
|
margin:0 0 2rem;font-size:.85rem}
|
|
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
|
|
border-bottom:1px solid var(--line);padding-bottom:.4rem}
|
|
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
|
|
.fmap a:hover{text-decoration:underline}
|
|
.fmap div{color:var(--faint);line-height:1.5}
|
|
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
|
|
|
|
@media (max-width:640px){
|
|
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
|
|
.btns{gap:.5rem}
|
|
.btn{padding:.75rem 1.15rem;font-size:.68rem}
|
|
.copy,.copy .btn{width:100%;justify-content:center}
|
|
.menu{left:0;right:0;min-width:0}
|
|
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
|
|
.strip b{border-right:0;padding-right:0}
|
|
.bar{width:100%}
|
|
}
|
|
</style>
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/realtime-websocket-implementation">
|
|
<link rel="alternate" type="text/markdown" href="/realtime-websocket-implementation.md">
|
|
<script type="module" src="/webmcp.js"></script>
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/realtime-websocket-implementation.md
|
|
Index: https://hanzoskills.com/llms.txt
|
|
Corpus: https://hanzoskills.com/all.md
|
|
Append .md to any path for the markdown twin. -->
|
|
<body>
|
|
<nav><div class="in">
|
|
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
|
|
<a class="up" href="/">All skills</a>
|
|
</div></nav>
|
|
|
|
<div class="wrap">
|
|
<h1>realtime-websocket-implementation</h1><p class="lede">Scope: WebSocket protocol, connection management, reconnection strategies, and heartbeat patterns Lines: 387 Last Updated: 2025-10-18</p><h1>WebSocket Implementation</h1>
|
|
<p><strong>Scope</strong>: WebSocket protocol, connection management, reconnection strategies, and heartbeat patterns <strong>Lines</strong>: 387 <strong>Last Updated</strong>: 2025-10-18</p>
|
|
<h2>When to Use This Skill</h2>
|
|
<p>Use WebSocket implementation when you need:</p>
|
|
<ul><li><strong>Bidirectional communication</strong>: Full-duplex communication between client and server</li><li><strong>Low latency</strong>: Sub-100ms message delivery for chat, gaming, or trading applications</li><li><strong>Server push</strong>: Server needs to push updates without client polling</li><li><strong>Persistent connections</strong>: Long-lived connections for real-time data streams</li><li><strong>Binary data</strong>: Efficient transmission of binary protocols (protobuf, MessagePack)</li></ul>
|
|
<p><strong>Don't use</strong> when:</p>
|
|
<ul><li>Unidirectional data flow is sufficient (use Server-Sent Events)</li><li>Client is behind restrictive proxies (WebSocket may be blocked)</li><li>Simple HTTP requests would suffice (REST APIs are simpler)</li><li>Broadcasting to many clients without client->server messages (SSE is lighter)</li></ul>
|
|
<h2>Core Concepts</h2>
|
|
<h3>WebSocket Protocol</h3>
|
|
<pre><code>Client Server
|
|
| |
|
|
|-- HTTP Upgrade Request ------->|
|
|
| |
|
|
|<-- 101 Switching Protocols ----|
|
|
| |
|
|
|<====== WebSocket Frames ======>|
|
|
| |
|
|
|-- Close Frame ---------------->|
|
|
|<-- Close Frame ----------------|</code></pre>
|
|
<p><strong>Key Features</strong>:</p>
|
|
<ul><li>Upgrade from HTTP/1.1 to WebSocket protocol</li><li>Frame-based messaging (text or binary)</li><li>Built-in ping/pong for connection health</li><li>Close handshake for graceful shutdown</li></ul>
|
|
<h3>Connection States</h3>
|
|
<pre><code>CONNECTING (0) → Handshake in progress
|
|
OPEN (1) → Connection established, can send/receive
|
|
CLOSING (2) → Close handshake started
|
|
CLOSED (3) → Connection closed or failed</code></pre>
|
|
<h3>Frame Types</h3>
|
|
<pre><code>- Text frames: UTF-8 encoded strings
|
|
- Binary frames: Raw binary data
|
|
- Ping/Pong frames: Connection health check
|
|
- Close frames: Connection termination
|
|
- Continuation frames: Fragmented messages</code></pre>
|
|
<h2>Patterns</h2>
|
|
<h3>1. Basic Client Implementation (Browser)</h3>
|
|
<pre><code class="lang-typescript">// TypeScript/JavaScript client
|
|
class WebSocketClient {
|
|
private ws: WebSocket | null = null;
|
|
private url: string;
|
|
private reconnectAttempts = 0;
|
|
private maxReconnectAttempts = 5;
|
|
private reconnectDelay = 1000;
|
|
private heartbeatInterval: number | null = null;
|
|
private messageHandlers: Map<string, (data: any) => void> = new Map();
|
|
|
|
constructor(url: string) {
|
|
this.url = url;
|
|
}
|
|
|
|
connect(): Promise<void> {
|
|
return new Promise((resolve, reject) => {
|
|
this.ws = new WebSocket(this.url);
|
|
|
|
this.ws.onopen = () => {
|
|
console.log('WebSocket connected');
|
|
this.reconnectAttempts = 0;
|
|
this.startHeartbeat();
|
|
resolve();
|
|
};
|
|
|
|
this.ws.onmessage = (event) => {
|
|
this.handleMessage(event.data);
|
|
};
|
|
|
|
this.ws.onerror = (error) => {
|
|
console.error('WebSocket error:', error);
|
|
reject(error);
|
|
};
|
|
|
|
this.ws.onclose = (event) => {
|
|
console.log('WebSocket closed:', event.code, event.reason);
|
|
this.stopHeartbeat();
|
|
this.handleReconnect();
|
|
};
|
|
});
|
|
}
|
|
|
|
private handleMessage(data: string) {
|
|
try {
|
|
const message = JSON.parse(data);
|
|
const handler = this.messageHandlers.get(message.type);
|
|
if (handler) {
|
|
handler(message.data);
|
|
}
|
|
} catch (error) {
|
|
console.error('Failed to parse message:', error);
|
|
}
|
|
}
|
|
|
|
on(type: string, handler: (data: any) => void) {
|
|
this.messageHandlers.set(type, handler);
|
|
}
|
|
|
|
send(type: string, data: any) {
|
|
if (this.ws?.readyState === WebSocket.OPEN) {
|
|
this.ws.send(JSON.stringify({ type, data }));
|
|
} else {
|
|
console.error('WebSocket not connected');
|
|
}
|
|
}
|
|
|
|
private startHeartbeat() {
|
|
this.heartbeatInterval = window.setInterval(() => {
|
|
if (this.ws?.readyState === WebSocket.OPEN) {
|
|
this.ws.send(JSON.stringify({ type: 'ping' }));
|
|
}
|
|
}, 30000); // 30 seconds
|
|
}
|
|
|
|
private stopHeartbeat() {
|
|
if (this.heartbeatInterval !== null) {
|
|
clearInterval(this.heartbeatInterval);
|
|
this.heartbeatInterval = null;
|
|
}
|
|
}
|
|
|
|
private handleReconnect() {
|
|
if (this.reconnectAttempts < this.maxReconnectAttempts) {
|
|
this.reconnectAttempts++;
|
|
const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
|
|
console.log(`Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);
|
|
setTimeout(() => this.connect(), delay);
|
|
} else {
|
|
console.error('Max reconnection attempts reached');
|
|
}
|
|
}
|
|
|
|
close() {
|
|
this.stopHeartbeat();
|
|
this.ws?.close(1000, 'Client closing');
|
|
}
|
|
}
|
|
|
|
// Usage
|
|
const client = new WebSocketClient('wss://api.example.com/ws');
|
|
await client.connect();
|
|
|
|
client.on('message', (data) => {
|
|
console.log('Received:', data);
|
|
});
|
|
|
|
client.send('chat', { text: 'Hello, world!' });</code></pre>
|
|
<h3>2. Basic Server Implementation (Node.js)</h3>
|
|
<pre><code class="lang-typescript">// Using ws library
|
|
import { WebSocketServer, WebSocket } from 'ws';
|
|
import http from 'http';
|
|
|
|
interface Client {
|
|
ws: WebSocket;
|
|
id: string;
|
|
rooms: Set<string>;
|
|
lastPing: number;
|
|
}
|
|
|
|
class WebSocketServerManager {
|
|
private wss: WebSocketServer;
|
|
private clients: Map<string, Client> = new Map();
|
|
private rooms: Map<string, Set<string>> = new Map();
|
|
|
|
constructor(server: http.Server) {
|
|
this.wss = new WebSocketServer({ server });
|
|
this.initialize();
|
|
}
|
|
|
|
private initialize() {
|
|
this.wss.on('connection', (ws, req) => {
|
|
const id = this.generateClientId();
|
|
const client: Client = {
|
|
ws,
|
|
id,
|
|
rooms: new Set(),
|
|
lastPing: Date.now(),
|
|
};
|
|
|
|
this.clients.set(id, client);
|
|
console.log(`Client ${id} connected. Total clients: ${this.clients.size}`);
|
|
|
|
ws.on('message', (data) => {
|
|
this.handleMessage(client, data.toString());
|
|
});
|
|
|
|
ws.on('close', () => {
|
|
this.handleDisconnect(client);
|
|
});
|
|
|
|
ws.on('error', (error) => {
|
|
console.error(`Client ${id} error:`, error);
|
|
});
|
|
|
|
ws.on('pong', () => {
|
|
client.lastPing = Date.now();
|
|
});
|
|
|
|
// Send welcome message
|
|
this.sendToClient(client, 'connected', { id });
|
|
});
|
|
|
|
// Start heartbeat check
|
|
this.startHeartbeat();
|
|
}
|
|
|
|
private handleMessage(client: Client, data: string) {
|
|
try {
|
|
const message = JSON.parse(data);
|
|
|
|
switch (message.type) {
|
|
case 'ping':
|
|
this.sendToClient(client, 'pong', {});
|
|
break;
|
|
case 'join':
|
|
this.joinRoom(client, message.data.room);
|
|
break;
|
|
case 'leave':
|
|
this.leaveRoom(client, message.data.room);
|
|
break;
|
|
case 'broadcast':
|
|
this.broadcast(message.data.room, message.data);
|
|
break;
|
|
default:
|
|
console.log(`Unknown message type: ${message.type}`);
|
|
}
|
|
} catch (error) {
|
|
console.error('Failed to parse message:', error);
|
|
}
|
|
}
|
|
|
|
private sendToClient(client: Client, type: string, data: any) {
|
|
if (client.ws.readyState === WebSocket.OPEN) {
|
|
client.ws.send(JSON.stringify({ type, data }));
|
|
}
|
|
}
|
|
|
|
private joinRoom(client: Client, room: string) {
|
|
client.rooms.add(room);
|
|
if (!this.rooms.has(room)) {
|
|
this.rooms.set(room, new Set());
|
|
}
|
|
this.rooms.get(room)!.add(client.id);
|
|
console.log(`Client ${client.id} joined room ${room}`);
|
|
}
|
|
|
|
private leaveRoom(client: Client, room: string) {
|
|
client.rooms.delete(room);
|
|
this.rooms.get(room)?.delete(client.id);
|
|
console.log(`Client ${client.id} left room ${room}`);
|
|
}
|
|
|
|
private broadcast(room: string, data: any) {
|
|
const clientIds = this.rooms.get(room);
|
|
if (!clientIds) return;
|
|
|
|
clientIds.forEach((clientId) => {
|
|
const client = this.clients.get(clientId);
|
|
if (client) {
|
|
this.sendToClient(client, 'broadcast', data);
|
|
}
|
|
});
|
|
}
|
|
|
|
private handleDisconnect(client: Client) {
|
|
// Remove from all rooms
|
|
client.rooms.forEach((room) => {
|
|
this.rooms.get(room)?.delete(client.id);
|
|
});
|
|
this.clients.delete(client.id);
|
|
console.log(`Client ${client.id} disconnected. Total clients: ${this.clients.size}`);
|
|
}
|
|
|
|
private startHeartbeat() {
|
|
setInterval(() => {
|
|
const now = Date.now();
|
|
this.clients.forEach((client) => {
|
|
if (now - client.lastPing > 60000) {
|
|
// No ping in 60 seconds, close connection
|
|
console.log(`Client ${client.id} timeout`);
|
|
client.ws.terminate();
|
|
return;
|
|
}
|
|
|
|
if (client.ws.readyState === WebSocket.OPEN) {
|
|
client.ws.ping();
|
|
}
|
|
});
|
|
}, 30000); // Check every 30 seconds
|
|
}
|
|
|
|
private generateClientId(): string {
|
|
return `client_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
}
|
|
}
|
|
|
|
// Usage
|
|
const server = http.createServer();
|
|
const wsManager = new WebSocketServerManager(server);
|
|
server.listen(8080);</code></pre>
|
|
<h3>3. Exponential Backoff Reconnection</h3>
|
|
<pre><code class="lang-typescript">class ReconnectingWebSocket {
|
|
private url: string;
|
|
private ws: WebSocket | null = null;
|
|
private reconnectAttempts = 0;
|
|
private maxReconnectDelay = 30000;
|
|
private minReconnectDelay = 1000;
|
|
private reconnectDecay = 1.5;
|
|
private shouldReconnect = true;
|
|
|
|
constructor(url: string) {
|
|
this.url = url;
|
|
}
|
|
|
|
connect(): Promise<void> {
|
|
return new Promise((resolve, reject) => {
|
|
this.ws = new WebSocket(this.url);
|
|
|
|
const timeout = setTimeout(() => {
|
|
this.ws?.close();
|
|
reject(new Error('Connection timeout'));
|
|
}, 10000);
|
|
|
|
this.ws.onopen = () => {
|
|
clearTimeout(timeout);
|
|
this.reconnectAttempts = 0;
|
|
resolve();
|
|
};
|
|
|
|
this.ws.onclose = () => {
|
|
clearTimeout(timeout);
|
|
if (this.shouldReconnect) {
|
|
this.scheduleReconnect();
|
|
}
|
|
};
|
|
|
|
this.ws.onerror = (error) => {
|
|
clearTimeout(timeout);
|
|
reject(error);
|
|
};
|
|
});
|
|
}
|
|
|
|
private scheduleReconnect() {
|
|
const delay = Math.min(
|
|
this.minReconnectDelay * Math.pow(this.reconnectDecay, this.reconnectAttempts),
|
|
this.maxReconnectDelay
|
|
);
|
|
|
|
// Add jitter to prevent thundering herd
|
|
const jitter = delay * 0.1 * Math.random();
|
|
const totalDelay = delay + jitter;
|
|
|
|
this.reconnectAttempts++;
|
|
console.log(`Reconnecting in ${totalDelay.toFixed(0)}ms (attempt ${this.reconnectAttempts})`);
|
|
|
|
setTimeout(() => {
|
|
if (this.shouldReconnect) {
|
|
this.connect().catch((error) => {
|
|
console.error('Reconnection failed:', error);
|
|
});
|
|
}
|
|
}, totalDelay);
|
|
}
|
|
|
|
disconnect() {
|
|
this.shouldReconnect = false;
|
|
this.ws?.close();
|
|
}
|
|
}</code></pre>
|
|
<h3>4. Authentication and Authorization</h3>
|
|
<pre><code class="lang-typescript">// Client-side: Send auth token on connection
|
|
class AuthenticatedWebSocket {
|
|
private ws: WebSocket | null = null;
|
|
|
|
async connect(url: string, token: string): Promise<void> {
|
|
return new Promise((resolve, reject) => {
|
|
// Option 1: Token in URL query parameter
|
|
this.ws = new WebSocket(`${url}?token=${token}`);
|
|
|
|
this.ws.onopen = () => {
|
|
// Option 2: Send auth message after connection
|
|
this.ws!.send(JSON.stringify({ type: 'auth', token }));
|
|
resolve();
|
|
};
|
|
|
|
this.ws.onerror = reject;
|
|
});
|
|
}
|
|
}
|
|
|
|
// Server-side: Verify token
|
|
interface AuthenticatedClient extends Client {
|
|
userId: string;
|
|
authenticated: boolean;
|
|
}
|
|
|
|
class AuthenticatedWebSocketServer {
|
|
private handleConnection(ws: WebSocket, req: http.IncomingMessage) {
|
|
const client: AuthenticatedClient = {
|
|
ws,
|
|
id: this.generateClientId(),
|
|
rooms: new Set(),
|
|
lastPing: Date.now(),
|
|
userId: '',
|
|
authenticated: false,
|
|
};
|
|
|
|
// Option 1: Extract token from URL
|
|
const url = new URL(req.url!, `http://${req.headers.host}`);
|
|
const token = url.searchParams.get('token');
|
|
|
|
if (token && this.verifyToken(token)) {
|
|
client.authenticated = true;
|
|
client.userId = this.getUserIdFromToken(token);
|
|
}
|
|
|
|
// Set authentication timeout
|
|
const authTimeout = setTimeout(() => {
|
|
if (!client.authenticated) {
|
|
ws.close(4001, 'Authentication timeout');
|
|
}
|
|
}, 5000);
|
|
|
|
ws.on('message', (data) => {
|
|
const message = JSON.parse(data.toString());
|
|
|
|
// Option 2: Handle auth message
|
|
if (message.type === 'auth') {
|
|
if (this.verifyToken(message.token)) {
|
|
client.authenticated = true;
|
|
client.userId = this.getUserIdFromToken(message.token);
|
|
clearTimeout(authTimeout);
|
|
this.sendToClient(client, 'auth_success', { userId: client.userId });
|
|
} else {
|
|
ws.close(4002, 'Invalid token');
|
|
}
|
|
return;
|
|
}
|
|
|
|
// Require authentication for other messages
|
|
if (!client.authenticated) {
|
|
ws.close(4003, 'Not authenticated');
|
|
return;
|
|
}
|
|
|
|
this.handleMessage(client, message);
|
|
});
|
|
}
|
|
|
|
private verifyToken(token: string): boolean {
|
|
// Implement JWT verification or session validation
|
|
return true; // Placeholder
|
|
}
|
|
|
|
private getUserIdFromToken(token: string): string {
|
|
// Extract user ID from token
|
|
return 'user_123'; // Placeholder
|
|
}
|
|
}</code></pre>
|
|
<h2>Quick Reference</h2>
|
|
<h3>Client Connection</h3>
|
|
<pre><code class="lang-typescript">// Basic connection
|
|
const ws = new WebSocket('wss://api.example.com/ws');
|
|
|
|
// With protocols
|
|
const ws = new WebSocket('wss://api.example.com/ws', ['v1.protocol']);
|
|
|
|
// Check state
|
|
ws.readyState // CONNECTING=0, OPEN=1, CLOSING=2, CLOSED=3
|
|
|
|
// Send data
|
|
ws.send('text message');
|
|
ws.send(new Uint8Array([1, 2, 3]));
|
|
ws.send(JSON.stringify({ type: 'message', data: {} }));</code></pre>
|
|
<h3>Event Handlers</h3>
|
|
<pre><code class="lang-typescript">ws.onopen = (event) => { /* Connection opened */ };
|
|
ws.onmessage = (event) => { /* Message received: event.data */ };
|
|
ws.onerror = (event) => { /* Error occurred */ };
|
|
ws.onclose = (event) => { /* Connection closed: event.code, event.reason */ };</code></pre>
|
|
<h3>Close Codes</h3>
|
|
<pre><code>1000: Normal closure
|
|
1001: Going away (page navigation)
|
|
1002: Protocol error
|
|
1003: Unsupported data
|
|
1006: Abnormal closure (no close frame)
|
|
1008: Policy violation
|
|
1009: Message too big
|
|
1011: Server error
|
|
4000-4999: Application-specific codes</code></pre>
|
|
<h3>Server Libraries</h3>
|
|
<pre><code class="lang-typescript">// Node.js: ws
|
|
import { WebSocketServer } from 'ws';
|
|
|
|
// Node.js: uWebSockets.js (high performance)
|
|
import uWS from 'uWebSockets.js';
|
|
|
|
// Python: websockets
|
|
import websockets
|
|
|
|
// Go: gorilla/websocket
|
|
import "github.com/gorilla/websocket"</code></pre>
|
|
<h2>Anti-Patterns</h2>
|
|
<h3>❌ No Reconnection Logic</h3>
|
|
<pre><code class="lang-typescript">// Wrong: No reconnection handling
|
|
const ws = new WebSocket(url);
|
|
ws.onclose = () => {
|
|
console.log('Disconnected'); // Connection lost forever
|
|
};</code></pre>
|
|
<p><strong>Why it's bad</strong>: Network issues, server restarts, or idle timeouts will permanently lose connection</p>
|
|
<p><strong>Better approach</strong>:</p>
|
|
<pre><code class="lang-typescript">class WebSocketClient {
|
|
private reconnect() {
|
|
setTimeout(() => this.connect(), this.getBackoffDelay());
|
|
}
|
|
}</code></pre>
|
|
<h3>❌ No Heartbeat/Keepalive</h3>
|
|
<pre><code class="lang-typescript">// Wrong: No connection health check
|
|
const ws = new WebSocket(url);
|
|
// Connection might be dead but readyState still shows OPEN</code></pre>
|
|
<p><strong>Why it's bad</strong>: Idle connections can be closed by proxies/load balancers without notification</p>
|
|
<p><strong>Better approach</strong>:</p>
|
|
<pre><code class="lang-typescript">setInterval(() => {
|
|
if (ws.readyState === WebSocket.OPEN) {
|
|
ws.send(JSON.stringify({ type: 'ping' }));
|
|
}
|
|
}, 30000);</code></pre>
|
|
<h3>❌ Sending Before Connection Open</h3>
|
|
<pre><code class="lang-typescript">// Wrong: Send immediately
|
|
const ws = new WebSocket(url);
|
|
ws.send('hello'); // Error: WebSocket is not open</code></pre>
|
|
<p><strong>Why it's bad</strong>: Messages sent before connection is established will throw errors</p>
|
|
<p><strong>Better approach</strong>:</p>
|
|
<pre><code class="lang-typescript">const ws = new WebSocket(url);
|
|
ws.onopen = () => {
|
|
ws.send('hello'); // Safe
|
|
};</code></pre>
|
|
<h3>❌ No Message Queuing During Reconnection</h3>
|
|
<pre><code class="lang-typescript">// Wrong: Drop messages during reconnection
|
|
send(data: any) {
|
|
if (this.ws?.readyState === WebSocket.OPEN) {
|
|
this.ws.send(data);
|
|
}
|
|
// Message is lost if not connected
|
|
}</code></pre>
|
|
<p><strong>Why it's bad</strong>: Messages sent during reconnection are silently lost</p>
|
|
<p><strong>Better approach</strong>:</p>
|
|
<pre><code class="lang-typescript">private queue: any[] = [];
|
|
|
|
send(data: any) {
|
|
if (this.ws?.readyState === WebSocket.OPEN) {
|
|
this.ws.send(data);
|
|
} else {
|
|
this.queue.push(data);
|
|
}
|
|
}
|
|
|
|
private flushQueue() {
|
|
while (this.queue.length > 0) {
|
|
this.ws!.send(this.queue.shift()!);
|
|
}
|
|
}</code></pre>
|
|
<h3>❌ No Error Handling for Invalid Messages</h3>
|
|
<pre><code class="lang-typescript">// Wrong: Assume all messages are valid JSON
|
|
ws.onmessage = (event) => {
|
|
const data = JSON.parse(event.data); // Can throw
|
|
handleMessage(data);
|
|
};</code></pre>
|
|
<p><strong>Why it's bad</strong>: Malformed messages crash the application</p>
|
|
<p><strong>Better approach</strong>:</p>
|
|
<pre><code class="lang-typescript">ws.onmessage = (event) => {
|
|
try {
|
|
const data = JSON.parse(event.data);
|
|
handleMessage(data);
|
|
} catch (error) {
|
|
console.error('Invalid message:', error);
|
|
}
|
|
};</code></pre>
|
|
<h2>Level 3: Resources</h2>
|
|
<h3>Comprehensive Reference</h3>
|
|
<p><strong>Location</strong>: <code>~/.hanzo/skills/realtime/websocket-implementation/resources/REFERENCE.md</code></p>
|
|
<p>The comprehensive reference (1,900+ lines) covers:</p>
|
|
<ul><li>WebSocket protocol fundamentals (RFC 6455)</li><li>Connection lifecycle (handshake, frames, close)</li><li>Frame structure and opcodes</li><li>Message types (text, binary, ping/pong, close)</li><li>Security considerations (origin validation, authentication, TLS)</li><li>Scaling patterns (sticky sessions, Redis pub/sub, message queues)</li><li>Reconnection strategies with exponential backoff</li><li>Server implementations (Node.js ws, Python websockets, Go gorilla)</li><li>Client implementations (browser, Node.js, Python)</li><li>Testing strategies (unit, integration, load)</li><li>Common patterns (chat, real-time dashboards, multiplayer games)</li><li>Comparison with alternatives (SSE, long polling, HTTP/2)</li><li>Production best practices (monitoring, logging, resource limits)</li><li>Troubleshooting guide</li><li>Performance optimization techniques</li></ul>
|
|
<h3>Testing & Analysis Scripts</h3>
|
|
<p><strong>Location</strong>: <code>~/.hanzo/skills/realtime/websocket-implementation/resources/scripts/</code></p>
|
|
<p><strong>test_websocket.py</strong> - WebSocket testing tool</p>
|
|
<ul><li>Test connectivity, echo, latency, ping/pong</li><li>Support for text and binary messages</li><li>Connection lifecycle testing</li><li>Large message handling</li><li>Reconnection testing</li><li>JSON output for CI/CD integration</li><li>Usage: <code>./test_websocket.py wss://api.example.com/ws --latency --count 20 --json</code></li></ul>
|
|
<p><strong>benchmark_connections.py</strong> - Connection benchmark tool</p>
|
|
<ul><li>Test concurrent connections (100s to 1000s)</li><li>Measure connection establishment time</li><li>Throughput metrics (messages/sec, bytes/sec)</li><li>Gradual ramp-up support</li><li>Duration-based load testing</li><li>Detailed per-connection statistics</li><li>Usage: <code>./benchmark_connections.py ws://localhost:8080 --connections 1000 --duration 60</code></li></ul>
|
|
<p><strong>analyze_traffic.sh</strong> - Traffic analysis tool</p>
|
|
<ul><li>Capture WebSocket traffic with tcpdump</li><li>Analyze with tshark for detailed inspection</li><li>WebSocket handshake detection</li><li>Frame type breakdown (text, binary, ping, pong, close)</li><li>Payload size statistics</li><li>Connection duration analysis</li><li>JSON output for tooling integration</li><li>Usage: <code>./analyze_traffic.sh --interface eth0 --port 8080 --duration 60 --analyze</code></li></ul>
|
|
<h3>Production Examples</h3>
|
|
<p><strong>Location</strong>: <code>~/.hanzo/skills/realtime/websocket-implementation/resources/examples/</code></p>
|
|
<p><strong>Node.js Server</strong> (<code>node/websocket-server.js</code>)</p>
|
|
<ul><li>Production-ready WebSocket server using 'ws' library</li><li>Room-based messaging with broadcast support</li><li>Rate limiting and connection metrics</li><li>Ping/pong heartbeat with timeout detection</li><li>Graceful shutdown handling</li><li>Health check and metrics endpoints</li><li>Message routing and validation</li></ul>
|
|
<p><strong>Node.js Client</strong> (<code>node/websocket-client.js</code>)</p>
|
|
<ul><li>Robust client with exponential backoff reconnection</li><li>Message queueing during disconnection</li><li>Heartbeat detection with automatic reconnect</li><li>State machine management</li><li>Event-driven architecture</li><li>TypeScript-ready implementation</li></ul>
|
|
<p><strong>Python Server</strong> (<code>python/websocket_server.py</code>)</p>
|
|
<ul><li>Async/await server using 'websockets' library</li><li>Room management and broadcasting</li><li>Token bucket rate limiting</li><li>Built-in ping/pong support</li><li>Metrics reporting</li><li>Signal handling for graceful shutdown</li></ul>
|
|
<p><strong>Python Client</strong> (<code>python/websocket_client.py</code>)</p>
|
|
<ul><li>Async client with reconnection logic</li><li>Message queueing and batching</li><li>Callback-based event handling</li><li>Heartbeat monitoring</li><li>Connection state tracking</li></ul>
|
|
<p><strong>React Hook</strong> (<code>react/useWebSocket.tsx</code>)</p>
|
|
<ul><li>Custom hook for React applications</li><li>Automatic reconnection with state management</li><li>Message queueing during reconnection</li><li>TypeScript support</li><li>Example components (chat room, connection status)</li><li>Optimized for React 18+ patterns</li></ul>
|
|
<p><strong>Docker Deployment</strong> (<code>docker/</code>)</p>
|
|
<ul><li>Multi-container setup with docker-compose</li><li>Scalable WebSocket servers with Redis pub/sub</li><li>Nginx load balancer with sticky sessions</li><li>Prometheus + Grafana monitoring</li><li>Health checks and auto-restart</li><li>Production-ready configuration</li></ul>
|
|
<h3>Usage Examples</h3>
|
|
<pre><code class="lang-bash"># Test WebSocket server connectivity and latency
|
|
./resources/scripts/test_websocket.py wss://api.example.com/ws --latency --count 10
|
|
|
|
# Benchmark 1000 concurrent connections
|
|
./resources/scripts/benchmark_connections.py ws://localhost:8080 \
|
|
--connections 1000 --duration 60 --ramp-up 30
|
|
|
|
# Analyze WebSocket traffic
|
|
./resources/scripts/analyze_traffic.sh \
|
|
--interface eth0 --port 8080 --duration 300 --analyze
|
|
|
|
# Run Node.js server
|
|
cd resources/examples/node && npm install && node websocket-server.js
|
|
|
|
# Run Python server
|
|
cd resources/examples/python && python websocket_server.py --port 8080
|
|
|
|
# Deploy with Docker
|
|
cd resources/examples/docker && docker-compose up -d
|
|
docker-compose scale websocket=3 # Scale to 3 instances</code></pre>
|
|
<h2>Related Skills</h2>
|
|
<ul><li><strong>server-sent-events.md</strong>: Alternative for unidirectional server-to-client streaming</li><li><strong>realtime-sync.md</strong>: Conflict resolution and data synchronization over WebSockets</li><li><strong>pubsub-patterns.md</strong>: Message routing and fan-out patterns for WebSocket servers</li><li><strong>network-resilience-patterns.md</strong>: Advanced retry, circuit breaker, and timeout patterns</li></ul>
|
|
<hr>
|
|
<p><strong>Last Updated</strong>: 2025-10-27 <strong>Format Version</strong>: 1.0 (Atomic)</p>
|
|
<footer>
|
|
<div class="fmap">
|
|
<div><b>Build</b>
|
|
<a href="https://hanzo.app">hanzo.app</a> app builder
|
|
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
|
|
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
|
|
<div><b>Run</b>
|
|
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
|
|
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
|
|
<div><b>Account</b>
|
|
<a href="https://hanzo.id">hanzo.id</a> sign in
|
|
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
|
|
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
|
|
<div><b>Company</b>
|
|
<a href="https://hanzo.ai">hanzo.ai</a> canonical
|
|
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
|
|
</div>
|
|
<div class="fend"><a href="/realtime-websocket-implementation.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |