mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
2764 lines
92 KiB
HTML
2764 lines
92 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>reference</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="alternate" type="text/markdown" href="/reference.md">
|
|
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/reference">
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/reference.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>reference</h1><p class="lede">1. Protocol Fundamentals(#protocol-fundamentals) 2.</p><h1>WebSocket Protocol - Comprehensive Reference</h1>
|
|
<h2>Table of Contents</h2>
|
|
<ol><li><a href="#protocol-fundamentals">Protocol Fundamentals</a></li><li><a href="#connection-lifecycle">Connection Lifecycle</a></li><li><a href="#frame-structure">Frame Structure</a></li><li><a href="#message-types">Message Types</a></li><li><a href="#security">Security</a></li><li><a href="#scaling-patterns">Scaling Patterns</a></li><li><a href="#reconnection-strategies">Reconnection Strategies</a></li><li><a href="#server-implementations">Server Implementations</a></li><li><a href="#client-implementations">Client Implementations</a></li><li><a href="#testing-strategies">Testing Strategies</a></li><li><a href="#common-patterns">Common Patterns</a></li><li><a href="#comparison-with-alternatives">Comparison with Alternatives</a></li><li><a href="#production-best-practices">Production Best Practices</a></li><li><a href="#troubleshooting">Troubleshooting</a></li><li><a href="#performance-optimization">Performance Optimization</a></li></ol>
|
|
<hr>
|
|
<h2>Protocol Fundamentals</h2>
|
|
<h3>RFC 6455 Overview</h3>
|
|
<p>WebSocket is a computer communications protocol providing full-duplex communication channels over a single TCP connection. Standardized by RFC 6455 in 2011, it enables real-time, bidirectional data exchange between client and server with lower overhead than HTTP polling.</p>
|
|
<p><strong>Key Characteristics</strong>:</p>
|
|
<ul><li>Full-duplex bidirectional communication</li><li>Single TCP connection</li><li>Low overhead (2-14 bytes per frame vs HTTP headers)</li><li>Works over HTTP ports (80/443)</li><li>Upgrades from HTTP via handshake</li><li>UTF-8 text or binary data</li><li>Built-in ping/pong for keepalive</li></ul>
|
|
<p><strong>Protocol URI Schemes</strong>:</p>
|
|
<pre><code>ws:// - Unencrypted WebSocket (like HTTP)
|
|
wss:// - Encrypted WebSocket over TLS (like HTTPS)</code></pre>
|
|
<h3>WebSocket vs HTTP</h3>
|
|
<p><strong>HTTP Request/Response</strong>:</p>
|
|
<pre><code>Client -> Server: GET /data HTTP/1.1
|
|
Server -> Client: 200 OK + data
|
|
[Connection closes or kept alive]
|
|
Client -> Server: New request needed for new data</code></pre>
|
|
<p><strong>WebSocket Persistent Connection</strong>:</p>
|
|
<pre><code>Client -> Server: Upgrade to WebSocket
|
|
Server -> Client: 101 Switching Protocols
|
|
[Connection remains open]
|
|
Client <-> Server: Bidirectional messages anytime</code></pre>
|
|
<p><strong>Overhead Comparison</strong>:</p>
|
|
<pre><code>HTTP Request Headers: ~200-800 bytes per request
|
|
HTTP Response Headers: ~200-500 bytes per response
|
|
Total per exchange: ~400-1300 bytes
|
|
|
|
WebSocket Frame: 2-14 bytes per message</code></pre>
|
|
<p>For 1000 messages:</p>
|
|
<ul><li>HTTP: 400KB - 1.3MB overhead</li><li>WebSocket: 2KB - 14KB overhead</li></ul>
|
|
<h3>Protocol Layers</h3>
|
|
<pre><code>┌─────────────────────────────────┐
|
|
│ Application Layer │
|
|
│ (Your application logic) │
|
|
├─────────────────────────────────┤
|
|
│ WebSocket Protocol │
|
|
│ (RFC 6455 - Framing/Messages) │
|
|
├─────────────────────────────────┤
|
|
│ TLS (for wss://) │
|
|
│ (Optional encryption) │
|
|
├─────────────────────────────────┤
|
|
│ TCP │
|
|
│ (Reliable transport) │
|
|
├─────────────────────────────────┤
|
|
│ IP │
|
|
│ (Network routing) │
|
|
└─────────────────────────────────┘</code></pre>
|
|
<h3>Use Cases</h3>
|
|
<p><strong>Ideal for</strong>:</p>
|
|
<ul><li>Real-time chat applications</li><li>Live sports/stock tickers</li><li>Multiplayer games</li><li>Collaborative editing (Google Docs-style)</li><li>Live dashboards/monitoring</li><li>IoT device communication</li><li>Live video streaming metadata</li><li>Trading platforms</li><li>Real-time notifications</li></ul>
|
|
<p><strong>Not ideal for</strong>:</p>
|
|
<ul><li>One-way server push (use SSE)</li><li>Infrequent updates (use HTTP polling)</li><li>REST API calls (use HTTP)</li><li>File uploads (use HTTP multipart)</li><li>Heavy proxy/firewall environments</li></ul>
|
|
<hr>
|
|
<h2>Connection Lifecycle</h2>
|
|
<h3>Phase 1: HTTP Upgrade Handshake</h3>
|
|
<p>The WebSocket connection begins as an HTTP request that "upgrades" to the WebSocket protocol.</p>
|
|
<p><strong>Client Handshake Request</strong>:</p>
|
|
<pre><code class="lang-http">GET /chat HTTP/1.1
|
|
Host: example.com
|
|
Upgrade: websocket
|
|
Connection: Upgrade
|
|
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
|
|
Sec-WebSocket-Version: 13
|
|
Origin: http://example.com
|
|
Sec-WebSocket-Protocol: chat, superchat
|
|
Sec-WebSocket-Extensions: permessage-deflate</code></pre>
|
|
<p><strong>Header Breakdown</strong>:</p>
|
|
<ul><li><code>Upgrade: websocket</code> - Request protocol upgrade</li><li><code>Connection: Upgrade</code> - Indicate connection will be upgraded</li><li><code>Sec-WebSocket-Key</code> - Random base64-encoded 16-byte value (security)</li><li><code>Sec-WebSocket-Version</code> - WebSocket protocol version (13 is current)</li><li><code>Origin</code> - Browser security (prevent CSRF)</li><li><code>Sec-WebSocket-Protocol</code> - Subprotocols (optional)</li><li><code>Sec-WebSocket-Extensions</code> - Extensions like compression (optional)</li></ul>
|
|
<p><strong>Server Handshake Response</strong>:</p>
|
|
<pre><code class="lang-http">HTTP/1.1 101 Switching Protocols
|
|
Upgrade: websocket
|
|
Connection: Upgrade
|
|
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
|
|
Sec-WebSocket-Protocol: chat
|
|
Sec-WebSocket-Extensions: permessage-deflate</code></pre>
|
|
<p><strong>Header Breakdown</strong>:</p>
|
|
<ul><li><code>101 Switching Protocols</code> - Upgrade accepted</li><li><code>Sec-WebSocket-Accept</code> - Computed from client's key (see below)</li><li><code>Sec-WebSocket-Protocol</code> - Selected subprotocol (if any)</li><li><code>Sec-WebSocket-Extensions</code> - Accepted extensions</li></ul>
|
|
<p><strong>Sec-WebSocket-Accept Calculation</strong>:</p>
|
|
<pre><code class="lang-javascript">// Server computes this from client's Sec-WebSocket-Key
|
|
const crypto = require('crypto');
|
|
|
|
function generateAcceptKey(clientKey) {
|
|
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; // RFC 6455 magic string
|
|
const hash = crypto
|
|
.createHash('sha1')
|
|
.update(clientKey + GUID)
|
|
.digest('base64');
|
|
return hash;
|
|
}
|
|
|
|
// Example:
|
|
const clientKey = 'dGhlIHNhbXBsZSBub25jZQ==';
|
|
const acceptKey = generateAcceptKey(clientKey);
|
|
// Returns: 's3pPLMBiTxaQ9kYGzzhZRbK+xOo='</code></pre>
|
|
<p>This prevents accidental WebSocket connections and ensures both sides understand the protocol.</p>
|
|
<h3>Phase 2: Data Transfer</h3>
|
|
<p>Once upgraded, the connection switches to WebSocket framing. Both client and server can send messages at any time.</p>
|
|
<p><strong>Message Flow</strong>:</p>
|
|
<pre><code>Client Server
|
|
| |
|
|
|-- Text Message -------------->|
|
|
| |
|
|
|<-- Text Message --------------|
|
|
| |
|
|
|-- Binary Message ------------>|
|
|
| |
|
|
|<-- Ping -----------------------|
|
|
|-- Pong ---------------------->|
|
|
| |</code></pre>
|
|
<p><strong>Multiplexing</strong>: A single WebSocket connection can carry multiple logical channels/topics by using message prefixes or JSON envelopes:</p>
|
|
<pre><code class="lang-javascript">// Topic-based routing
|
|
ws.send(JSON.stringify({
|
|
topic: 'chat',
|
|
data: { user: 'Alice', message: 'Hello' }
|
|
}));
|
|
|
|
ws.send(JSON.stringify({
|
|
topic: 'notifications',
|
|
data: { type: 'friend_request', from: 'Bob' }
|
|
}));</code></pre>
|
|
<h3>Phase 3: Connection Close</h3>
|
|
<p>Either side can initiate a close. The closing handshake ensures graceful shutdown.</p>
|
|
<p><strong>Close Handshake</strong>:</p>
|
|
<pre><code>Client Server
|
|
| |
|
|
|-- Close Frame (code 1000) --->|
|
|
| |
|
|
|<-- Close Frame (code 1000) ---|
|
|
| |
|
|
[TCP connection closes]</code></pre>
|
|
<p><strong>Close Codes</strong> (from RFC 6455):</p>
|
|
<pre><code>1000 - Normal Closure
|
|
1001 - Going Away (server shutdown, browser navigation)
|
|
1002 - Protocol Error
|
|
1003 - Unsupported Data (e.g., text-only but received binary)
|
|
1006 - Abnormal Closure (no close frame, connection lost)
|
|
1007 - Invalid Payload Data (malformed UTF-8 in text)
|
|
1008 - Policy Violation (generic)
|
|
1009 - Message Too Big
|
|
1010 - Mandatory Extension (client expected extension)
|
|
1011 - Internal Server Error
|
|
1015 - TLS Handshake Failure</code></pre>
|
|
<p><strong>Application-Defined Codes</strong>: 3000-4999 range for custom close reasons.</p>
|
|
<p><strong>Close Sequence</strong>:</p>
|
|
<pre><code class="lang-javascript">// Client initiates close
|
|
ws.close(1000, 'User logged out');
|
|
|
|
// Server receives close event
|
|
ws.on('close', (code, reason) => {
|
|
console.log(`Closed: ${code} - ${reason}`);
|
|
// Cleanup resources
|
|
});
|
|
|
|
// Server responds with close frame
|
|
// TCP connection terminates</code></pre>
|
|
<h3>State Transitions</h3>
|
|
<pre><code>CONNECTING (0)
|
|
↓
|
|
[Handshake completes]
|
|
↓
|
|
OPEN (1)
|
|
↓
|
|
[Close initiated]
|
|
↓
|
|
CLOSING (2)
|
|
↓
|
|
[Close handshake completes]
|
|
↓
|
|
CLOSED (3)</code></pre>
|
|
<p><strong>Browser WebSocket API States</strong>:</p>
|
|
<pre><code class="lang-javascript">WebSocket.CONNECTING // 0
|
|
WebSocket.OPEN // 1
|
|
WebSocket.CLOSING // 2
|
|
WebSocket.CLOSED // 3
|
|
|
|
// Check state
|
|
if (ws.readyState === WebSocket.OPEN) {
|
|
ws.send('message');
|
|
}</code></pre>
|
|
<h3>Connection Errors</h3>
|
|
<p><strong>Common Failure Modes</strong>:</p>
|
|
<ol><li><strong>Handshake Rejection</strong>: Server returns non-101 status</li><li><strong>Network Interruption</strong>: Connection drops without close frame</li><li><strong>Timeout</strong>: No data received for extended period</li><li><strong>Protocol Violation</strong>: Invalid frame received</li><li><strong>TLS Failure</strong>: Certificate issues on wss://</li></ol>
|
|
<p><strong>Error Handling</strong>:</p>
|
|
<pre><code class="lang-javascript">ws.on('error', (error) => {
|
|
console.error('WebSocket error:', error);
|
|
// Attempt reconnection if appropriate
|
|
});
|
|
|
|
ws.on('close', (code, reason) => {
|
|
if (code !== 1000) {
|
|
console.error(`Abnormal close: ${code} - ${reason}`);
|
|
// Trigger reconnection logic
|
|
}
|
|
});</code></pre>
|
|
<hr>
|
|
<h2>Frame Structure</h2>
|
|
<p>WebSocket uses a binary framing protocol. Each message is split into one or more frames.</p>
|
|
<h3>Frame Format</h3>
|
|
<pre><code> 0 1 2 3
|
|
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
|
|
+-+-+-+-+-------+-+-------------+-------------------------------+
|
|
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|
|
|I|S|S|S| (4) |A| (7) | (16/64) |
|
|
|N|V|V|V| |S| | (if payload len==126/127) |
|
|
| |1|2|3| |K| | |
|
|
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
|
|
| Extended payload length continued, if payload len == 127 |
|
|
+ - - - - - - - - - - - - - - - +-------------------------------+
|
|
| |Masking-key, if MASK set to 1 |
|
|
+-------------------------------+-------------------------------+
|
|
| Masking-key (continued) | Payload Data |
|
|
+-------------------------------- - - - - - - - - - - - - - - - +
|
|
: Payload Data continued ... :
|
|
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
|
|
| Payload Data continued ... |
|
|
+---------------------------------------------------------------+</code></pre>
|
|
<h3>Field Descriptions</h3>
|
|
<p><strong>FIN (1 bit)</strong>:</p>
|
|
<ul><li><code>1</code> = Final fragment in message</li><li><code>0</code> = More fragments follow</li><li>Allows message fragmentation</li></ul>
|
|
<p><strong>RSV1, RSV2, RSV3 (1 bit each)</strong>:</p>
|
|
<ul><li>Reserved for extensions</li><li>Must be 0 unless extension defines usage</li><li>Example: RSV1 = 1 for permessage-deflate compression</li></ul>
|
|
<p><strong>Opcode (4 bits)</strong>:</p>
|
|
<pre><code>0x0 - Continuation frame
|
|
0x1 - Text frame (UTF-8)
|
|
0x2 - Binary frame
|
|
0x8 - Connection close
|
|
0x9 - Ping
|
|
0xA - Pong
|
|
0x3-0x7 - Reserved for future data frames
|
|
0xB-0xF - Reserved for future control frames</code></pre>
|
|
<p><strong>MASK (1 bit)</strong>:</p>
|
|
<ul><li><code>1</code> = Payload is masked (MUST be 1 for client->server)</li><li><code>0</code> = Payload is not masked (server->client)</li><li>Prevents cache poisoning attacks</li></ul>
|
|
<p><strong>Payload Length (7 bits, 7+16 bits, or 7+64 bits)</strong>:</p>
|
|
<pre><code>0-125: Actual payload length
|
|
126: Next 2 bytes are 16-bit length
|
|
127: Next 8 bytes are 64-bit length</code></pre>
|
|
<p><strong>Masking Key (0 or 4 bytes)</strong>:</p>
|
|
<ul><li>Present if MASK bit is set</li><li>Random 32-bit value</li><li>Used to XOR payload data</li></ul>
|
|
<p><strong>Payload Data</strong>:</p>
|
|
<ul><li>Extension data (if negotiated) + Application data</li><li>Masked if from client</li></ul>
|
|
<h3>Masking Algorithm</h3>
|
|
<p>Client-to-server frames MUST be masked to prevent cache poisoning:</p>
|
|
<pre><code class="lang-javascript">function maskPayload(payload, maskingKey) {
|
|
const masked = Buffer.alloc(payload.length);
|
|
for (let i = 0; i < payload.length; i++) {
|
|
masked[i] = payload[i] ^ maskingKey[i % 4];
|
|
}
|
|
return masked;
|
|
}
|
|
|
|
// Example
|
|
const payload = Buffer.from('Hello');
|
|
const maskingKey = Buffer.from([0x12, 0x34, 0x56, 0x78]);
|
|
const masked = maskPayload(payload, maskingKey);
|
|
|
|
// Unmask (server-side)
|
|
const unmasked = maskPayload(masked, maskingKey); // XOR is reversible
|
|
// unmasked equals original payload</code></pre>
|
|
<h3>Frame Examples</h3>
|
|
<p><strong>Simple Text Message</strong> (client->server):</p>
|
|
<pre><code>"Hi" (2 bytes payload)
|
|
|
|
0x81 0x82 [mask] [masked payload]
|
|
|
|
Breakdown:
|
|
0x81 = 10000001
|
|
- FIN=1 (final fragment)
|
|
- RSV=000
|
|
- Opcode=0001 (text)
|
|
|
|
0x82 = 10000010
|
|
- MASK=1
|
|
- Length=2
|
|
|
|
[4 bytes masking key]
|
|
[2 bytes masked payload]
|
|
|
|
Total: 8 bytes</code></pre>
|
|
<p><strong>Ping Frame</strong> (server->client):</p>
|
|
<pre><code>0x89 0x00
|
|
|
|
Breakdown:
|
|
0x89 = 10001001
|
|
- FIN=1
|
|
- RSV=000
|
|
- Opcode=1001 (ping)
|
|
|
|
0x00 = 00000000
|
|
- MASK=0
|
|
- Length=0
|
|
|
|
Total: 2 bytes</code></pre>
|
|
<p><strong>Large Binary Message</strong> (server->client, 65KB):</p>
|
|
<pre><code>0x82 0x7E [2-byte length] [payload]
|
|
|
|
Breakdown:
|
|
0x82 = 10000010
|
|
- FIN=1
|
|
- Opcode=0010 (binary)
|
|
|
|
0x7E = 01111110
|
|
- MASK=0
|
|
- Length=126 (indicates next 2 bytes are length)
|
|
|
|
[2 bytes: 0xFF 0xFF = 65535]
|
|
[65535 bytes payload]
|
|
|
|
Total: 4 + 65535 = 65539 bytes</code></pre>
|
|
<h3>Fragmentation</h3>
|
|
<p>Large messages can be split into multiple frames:</p>
|
|
<pre><code>Frame 1: FIN=0, Opcode=0x1 (text), Payload="Hello "
|
|
Frame 2: FIN=0, Opcode=0x0 (continuation), Payload="World"
|
|
Frame 3: FIN=1, Opcode=0x0 (continuation), Payload="!"
|
|
|
|
Reassembled: "Hello World!"</code></pre>
|
|
<p><strong>Fragmentation Rules</strong>:</p>
|
|
<ul><li>First frame has message opcode (text/binary)</li><li>Subsequent frames have opcode 0x0 (continuation)</li><li>Control frames (ping/pong/close) can be interleaved</li><li>Control frames MUST NOT be fragmented</li></ul>
|
|
<p><strong>Example with Interleaved Ping</strong>:</p>
|
|
<pre><code>Frame 1: FIN=0, Opcode=0x1 (text), Payload="Start"
|
|
Frame 2: FIN=1, Opcode=0x9 (ping), Payload=""
|
|
Frame 3: FIN=1, Opcode=0xA (pong), Payload=""
|
|
Frame 4: FIN=1, Opcode=0x0 (continuation), Payload="End"
|
|
|
|
Text message: "StartEnd"
|
|
Ping/Pong: Handled separately</code></pre>
|
|
<h3>Control Frames</h3>
|
|
<p><strong>Characteristics</strong>:</p>
|
|
<ul><li>Opcode >= 0x8</li><li>MUST NOT be fragmented</li><li>Payload <= 125 bytes</li><li>Can be injected mid-message</li></ul>
|
|
<p><strong>Close Frame Payload</strong>:</p>
|
|
<pre><code>[2-byte status code] [UTF-8 reason]
|
|
|
|
Example:
|
|
0x03 0xE8 "Going away"
|
|
= 1000 "Going away"</code></pre>
|
|
<p><strong>Ping/Pong Application Data</strong>:</p>
|
|
<pre><code>Ping: 0x89 0x05 "12345"
|
|
Pong: 0x8A 0x05 "12345" (echoes ping data)</code></pre>
|
|
<hr>
|
|
<h2>Message Types</h2>
|
|
<h3>Text Messages</h3>
|
|
<p><strong>Characteristics</strong>:</p>
|
|
<ul><li>Opcode: 0x1</li><li>Payload MUST be valid UTF-8</li><li>Server MUST close connection on invalid UTF-8 (code 1007)</li></ul>
|
|
<p><strong>Sending</strong>:</p>
|
|
<pre><code class="lang-javascript">// Browser
|
|
ws.send('Hello World');
|
|
ws.send(JSON.stringify({ type: 'chat', msg: 'Hi' }));
|
|
|
|
// Node.js (ws library)
|
|
ws.send('Hello World', { binary: false });</code></pre>
|
|
<p><strong>Receiving</strong>:</p>
|
|
<pre><code class="lang-javascript">ws.onmessage = (event) => {
|
|
if (typeof event.data === 'string') {
|
|
console.log('Text:', event.data);
|
|
const obj = JSON.parse(event.data);
|
|
}
|
|
};</code></pre>
|
|
<p><strong>UTF-8 Validation</strong>:</p>
|
|
<pre><code class="lang-javascript">// Server must validate
|
|
function isValidUTF8(buffer) {
|
|
try {
|
|
buffer.toString('utf8');
|
|
return true;
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
ws.on('message', (data, isBinary) => {
|
|
if (!isBinary && !isValidUTF8(data)) {
|
|
ws.close(1007, 'Invalid UTF-8');
|
|
}
|
|
});</code></pre>
|
|
<p><strong>Common JSON Envelope Pattern</strong>:</p>
|
|
<pre><code class="lang-javascript">// Structured message format
|
|
const message = {
|
|
type: 'event_type',
|
|
id: 'unique_id',
|
|
timestamp: Date.now(),
|
|
data: { /* payload */ }
|
|
};
|
|
|
|
ws.send(JSON.stringify(message));</code></pre>
|
|
<h3>Binary Messages</h3>
|
|
<p><strong>Characteristics</strong>:</p>
|
|
<ul><li>Opcode: 0x2</li><li>Raw binary data</li><li>No encoding constraints</li></ul>
|
|
<p><strong>Sending</strong>:</p>
|
|
<pre><code class="lang-javascript">// Browser - ArrayBuffer
|
|
const buffer = new ArrayBuffer(8);
|
|
const view = new DataView(buffer);
|
|
view.setUint32(0, 12345678);
|
|
ws.send(buffer);
|
|
|
|
// Browser - Blob
|
|
const blob = new Blob(['binary data'], { type: 'application/octet-stream' });
|
|
ws.send(blob);
|
|
|
|
// Node.js - Buffer
|
|
const buf = Buffer.from([0x01, 0x02, 0x03]);
|
|
ws.send(buf, { binary: true });</code></pre>
|
|
<p><strong>Receiving</strong>:</p>
|
|
<pre><code class="lang-javascript">// Browser
|
|
ws.binaryType = 'arraybuffer'; // or 'blob'
|
|
|
|
ws.onmessage = (event) => {
|
|
if (event.data instanceof ArrayBuffer) {
|
|
const view = new DataView(event.data);
|
|
const value = view.getUint32(0);
|
|
}
|
|
};
|
|
|
|
// Node.js
|
|
ws.on('message', (data, isBinary) => {
|
|
if (isBinary) {
|
|
console.log('Binary:', data); // Buffer
|
|
}
|
|
});</code></pre>
|
|
<p><strong>Use Cases</strong>:</p>
|
|
<ul><li>Image/video streaming</li><li>Audio data</li><li>Protocol buffers / MessagePack</li><li>Game state (packed binary formats)</li><li>Sensor data</li></ul>
|
|
<h3>Ping/Pong Frames</h3>
|
|
<p><strong>Purpose</strong>:</p>
|
|
<ul><li>Keep connection alive</li><li>Detect broken connections</li><li>Measure latency</li></ul>
|
|
<p><strong>Ping Frame</strong>:</p>
|
|
<ul><li>Opcode: 0x9</li><li>Optional payload (max 125 bytes)</li><li>Recipient MUST respond with Pong</li></ul>
|
|
<p><strong>Pong Frame</strong>:</p>
|
|
<ul><li>Opcode: 0xA</li><li>MUST echo Ping payload</li><li>Can be sent unsolicited (heartbeat)</li></ul>
|
|
<p><strong>Browser Limitation</strong>: JavaScript WebSocket API doesn't expose ping/pong directly (browser handles automatically).</p>
|
|
<p><strong>Server-Side Ping</strong> (Node.js ws):</p>
|
|
<pre><code class="lang-javascript">const ws = new WebSocket.Server({ port: 8080 });
|
|
|
|
ws.on('connection', (socket) => {
|
|
const interval = setInterval(() => {
|
|
if (socket.readyState === WebSocket.OPEN) {
|
|
socket.ping();
|
|
}
|
|
}, 30000); // Every 30 seconds
|
|
|
|
socket.on('pong', () => {
|
|
console.log('Pong received');
|
|
});
|
|
|
|
socket.on('close', () => {
|
|
clearInterval(interval);
|
|
});
|
|
});</code></pre>
|
|
<p><strong>Client-Side Pong</strong> (automatic in most libraries):</p>
|
|
<pre><code class="lang-javascript">// Most libraries auto-respond to ping
|
|
// Manual pong (if needed):
|
|
ws.on('ping', (data) => {
|
|
ws.pong(data);
|
|
});</code></pre>
|
|
<p><strong>Latency Measurement</strong>:</p>
|
|
<pre><code class="lang-javascript">let pingStart;
|
|
|
|
const interval = setInterval(() => {
|
|
pingStart = Date.now();
|
|
ws.ping();
|
|
}, 5000);
|
|
|
|
ws.on('pong', () => {
|
|
const latency = Date.now() - pingStart;
|
|
console.log(`Latency: ${latency}ms`);
|
|
});</code></pre>
|
|
<p><strong>Timeout Detection</strong>:</p>
|
|
<pre><code class="lang-javascript">const PING_INTERVAL = 30000;
|
|
const PONG_TIMEOUT = 5000;
|
|
|
|
let pingTimeout;
|
|
|
|
function heartbeat() {
|
|
clearTimeout(pingTimeout);
|
|
pingTimeout = setTimeout(() => {
|
|
console.log('Connection timed out');
|
|
ws.terminate(); // Force close
|
|
}, PONG_TIMEOUT);
|
|
}
|
|
|
|
const interval = setInterval(() => {
|
|
ws.ping();
|
|
heartbeat();
|
|
}, PING_INTERVAL);
|
|
|
|
ws.on('pong', () => {
|
|
heartbeat();
|
|
});
|
|
|
|
ws.on('close', () => {
|
|
clearInterval(interval);
|
|
clearTimeout(pingTimeout);
|
|
});</code></pre>
|
|
<h3>Close Frames</h3>
|
|
<p><strong>Close Frame Structure</strong>:</p>
|
|
<pre><code>[2-byte status code] [optional UTF-8 reason]</code></pre>
|
|
<p><strong>Common Patterns</strong>:</p>
|
|
<pre><code class="lang-javascript">// Normal closure
|
|
ws.close(1000, 'Goodbye');
|
|
|
|
// Application error
|
|
ws.close(4000, 'Authentication failed');
|
|
|
|
// Policy violation
|
|
ws.close(1008, 'Rate limit exceeded');
|
|
|
|
// Going away
|
|
ws.close(1001, 'Server shutting down');</code></pre>
|
|
<p><strong>Graceful Shutdown</strong>:</p>
|
|
<pre><code class="lang-javascript">// Server shutdown
|
|
process.on('SIGTERM', () => {
|
|
wss.clients.forEach((ws) => {
|
|
ws.close(1001, 'Server shutting down');
|
|
});
|
|
|
|
setTimeout(() => {
|
|
process.exit(0);
|
|
}, 5000);
|
|
});</code></pre>
|
|
<p><strong>Close Handshake Timeout</strong>:</p>
|
|
<pre><code class="lang-javascript">ws.on('close', (code, reason) => {
|
|
console.log(`Closed: ${code} - ${reason}`);
|
|
});
|
|
|
|
// Force close if handshake takes too long
|
|
const closeTimeout = setTimeout(() => {
|
|
ws.terminate(); // Forceful close
|
|
}, 3000);
|
|
|
|
ws.on('close', () => {
|
|
clearTimeout(closeTimeout);
|
|
});</code></pre>
|
|
<hr>
|
|
<h2>Security</h2>
|
|
<h3>Origin Validation</h3>
|
|
<p>The <code>Origin</code> header (sent by browsers) must be validated to prevent CSRF attacks.</p>
|
|
<p><strong>Attack Scenario</strong>:</p>
|
|
<pre><code>1. User logged into trusted.com (has WebSocket connection)
|
|
2. User visits evil.com
|
|
3. evil.com JavaScript tries: new WebSocket('wss://trusted.com/ws')
|
|
4. Without origin check, connection succeeds with user's cookies</code></pre>
|
|
<p><strong>Server-Side Validation</strong>:</p>
|
|
<pre><code class="lang-javascript">const ALLOWED_ORIGINS = [
|
|
'https://trusted.com',
|
|
'https://app.trusted.com'
|
|
];
|
|
|
|
wss.on('connection', (ws, req) => {
|
|
const origin = req.headers.origin;
|
|
|
|
if (!ALLOWED_ORIGINS.includes(origin)) {
|
|
ws.close(1008, 'Origin not allowed');
|
|
return;
|
|
}
|
|
|
|
// Continue with connection
|
|
});</code></pre>
|
|
<p><strong>Development vs Production</strong>:</p>
|
|
<pre><code class="lang-javascript">const ALLOWED_ORIGINS = process.env.NODE_ENV === 'production'
|
|
? ['https://app.example.com']
|
|
: ['http://localhost:3000', 'http://localhost:5173'];</code></pre>
|
|
<h3>Authentication</h3>
|
|
<p>WebSocket doesn't have built-in authentication. Common patterns:</p>
|
|
<p><strong>1. Token in Query String</strong>:</p>
|
|
<pre><code class="lang-javascript">// Client
|
|
const token = await getAuthToken();
|
|
const ws = new WebSocket(`wss://api.example.com/ws?token=${token}`);
|
|
|
|
// Server
|
|
wss.on('connection', (ws, req) => {
|
|
const url = new URL(req.url, 'wss://api.example.com');
|
|
const token = url.searchParams.get('token');
|
|
|
|
if (!verifyToken(token)) {
|
|
ws.close(1008, 'Invalid token');
|
|
return;
|
|
}
|
|
|
|
ws.userId = extractUserId(token);
|
|
});</code></pre>
|
|
<p><strong>Caution</strong>: Tokens in URLs may be logged. Use wss:// to encrypt.</p>
|
|
<p><strong>2. Token in Subprotocol</strong>:</p>
|
|
<pre><code class="lang-javascript">// Client
|
|
const ws = new WebSocket('wss://api.example.com/ws', ['access_token', token]);
|
|
|
|
// Server
|
|
wss.on('connection', (ws, req) => {
|
|
const protocol = req.headers['sec-websocket-protocol'];
|
|
const [_, token] = protocol.split(', ');
|
|
|
|
if (!verifyToken(token)) {
|
|
ws.close(1008, 'Invalid token');
|
|
return;
|
|
}
|
|
});</code></pre>
|
|
<p><strong>3. Cookie-Based</strong> (if same-origin):</p>
|
|
<pre><code class="lang-javascript">// Cookies sent automatically in handshake
|
|
wss.on('connection', (ws, req) => {
|
|
const cookies = parseCookies(req.headers.cookie);
|
|
const sessionId = cookies['session_id'];
|
|
|
|
if (!validateSession(sessionId)) {
|
|
ws.close(1008, 'Invalid session');
|
|
return;
|
|
}
|
|
});</code></pre>
|
|
<p><strong>4. Post-Connection Authentication</strong>:</p>
|
|
<pre><code class="lang-javascript">// Client
|
|
const ws = new WebSocket('wss://api.example.com/ws');
|
|
|
|
ws.onopen = () => {
|
|
ws.send(JSON.stringify({
|
|
type: 'auth',
|
|
token: authToken
|
|
}));
|
|
};
|
|
|
|
// Server
|
|
const pendingAuth = new WeakMap();
|
|
|
|
wss.on('connection', (ws) => {
|
|
pendingAuth.set(ws, setTimeout(() => {
|
|
ws.close(1008, 'Authentication timeout');
|
|
}, 5000));
|
|
|
|
ws.on('message', (data) => {
|
|
const msg = JSON.parse(data);
|
|
|
|
if (msg.type === 'auth' && pendingAuth.has(ws)) {
|
|
clearTimeout(pendingAuth.get(ws));
|
|
pendingAuth.delete(ws);
|
|
|
|
if (verifyToken(msg.token)) {
|
|
ws.authenticated = true;
|
|
ws.userId = extractUserId(msg.token);
|
|
} else {
|
|
ws.close(1008, 'Invalid credentials');
|
|
}
|
|
} else if (!ws.authenticated) {
|
|
ws.close(1008, 'Not authenticated');
|
|
}
|
|
});
|
|
});</code></pre>
|
|
<h3>TLS/SSL (wss://)</h3>
|
|
<p><strong>Always use wss:// in production</strong>:</p>
|
|
<ul><li>Encrypts all data</li><li>Prevents eavesdropping</li><li>Prevents man-in-the-middle attacks</li><li>Required for browser security features</li></ul>
|
|
<p><strong>Certificate Setup</strong>:</p>
|
|
<pre><code class="lang-javascript">const https = require('https');
|
|
const WebSocket = require('ws');
|
|
const fs = require('fs');
|
|
|
|
const server = https.createServer({
|
|
cert: fs.readFileSync('/path/to/cert.pem'),
|
|
key: fs.readFileSync('/path/to/key.pem')
|
|
});
|
|
|
|
const wss = new WebSocket.Server({ server });
|
|
|
|
server.listen(8080);</code></pre>
|
|
<p><strong>Let's Encrypt with Certbot</strong>:</p>
|
|
<pre><code class="lang-bash">certbot certonly --standalone -d api.example.com
|
|
# Certificates in /etc/letsencrypt/live/api.example.com/</code></pre>
|
|
<h3>Rate Limiting</h3>
|
|
<p>Prevent abuse by limiting message frequency:</p>
|
|
<pre><code class="lang-javascript">const MESSAGE_LIMIT = 10;
|
|
const WINDOW_MS = 1000;
|
|
|
|
const rateLimits = new WeakMap();
|
|
|
|
wss.on('connection', (ws) => {
|
|
rateLimits.set(ws, {
|
|
count: 0,
|
|
resetTime: Date.now() + WINDOW_MS
|
|
});
|
|
|
|
ws.on('message', (data) => {
|
|
const limit = rateLimits.get(ws);
|
|
|
|
if (Date.now() > limit.resetTime) {
|
|
limit.count = 0;
|
|
limit.resetTime = Date.now() + WINDOW_MS;
|
|
}
|
|
|
|
limit.count++;
|
|
|
|
if (limit.count > MESSAGE_LIMIT) {
|
|
ws.close(1008, 'Rate limit exceeded');
|
|
return;
|
|
}
|
|
|
|
// Process message
|
|
});
|
|
});</code></pre>
|
|
<p><strong>Token Bucket Algorithm</strong>:</p>
|
|
<pre><code class="lang-javascript">class TokenBucket {
|
|
constructor(capacity, refillRate) {
|
|
this.capacity = capacity;
|
|
this.tokens = capacity;
|
|
this.refillRate = refillRate; // tokens per second
|
|
this.lastRefill = Date.now();
|
|
}
|
|
|
|
consume(tokens = 1) {
|
|
this.refill();
|
|
|
|
if (this.tokens >= tokens) {
|
|
this.tokens -= tokens;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
refill() {
|
|
const now = Date.now();
|
|
const elapsed = (now - this.lastRefill) / 1000;
|
|
const tokensToAdd = elapsed * this.refillRate;
|
|
|
|
this.tokens = Math.min(this.capacity, this.tokens + tokensToAdd);
|
|
this.lastRefill = now;
|
|
}
|
|
}
|
|
|
|
const buckets = new WeakMap();
|
|
|
|
wss.on('connection', (ws) => {
|
|
buckets.set(ws, new TokenBucket(100, 10)); // 100 capacity, 10/sec refill
|
|
|
|
ws.on('message', (data) => {
|
|
const bucket = buckets.get(ws);
|
|
|
|
if (!bucket.consume()) {
|
|
ws.send(JSON.stringify({ error: 'Rate limit exceeded' }));
|
|
return;
|
|
}
|
|
|
|
// Process message
|
|
});
|
|
});</code></pre>
|
|
<h3>Input Validation</h3>
|
|
<p>Always validate and sanitize incoming messages:</p>
|
|
<pre><code class="lang-javascript">ws.on('message', (data, isBinary) => {
|
|
// Size limit
|
|
if (data.length > 1024 * 1024) { // 1MB
|
|
ws.close(1009, 'Message too large');
|
|
return;
|
|
}
|
|
|
|
// Type validation
|
|
if (isBinary && !expectBinary) {
|
|
ws.close(1003, 'Unexpected binary data');
|
|
return;
|
|
}
|
|
|
|
// JSON parsing
|
|
let msg;
|
|
try {
|
|
msg = JSON.parse(data);
|
|
} catch (e) {
|
|
ws.send(JSON.stringify({ error: 'Invalid JSON' }));
|
|
return;
|
|
}
|
|
|
|
// Schema validation
|
|
if (!isValidSchema(msg)) {
|
|
ws.send(JSON.stringify({ error: 'Invalid message format' }));
|
|
return;
|
|
}
|
|
|
|
// Sanitize strings (prevent XSS if echoed to browser)
|
|
if (msg.text) {
|
|
msg.text = sanitizeHtml(msg.text);
|
|
}
|
|
|
|
// Process validated message
|
|
});</code></pre>
|
|
<h3>DoS Protection</h3>
|
|
<p><strong>Connection Limits</strong>:</p>
|
|
<pre><code class="lang-javascript">const MAX_CONNECTIONS_PER_IP = 10;
|
|
const connections = new Map();
|
|
|
|
wss.on('connection', (ws, req) => {
|
|
const ip = req.socket.remoteAddress;
|
|
const count = connections.get(ip) || 0;
|
|
|
|
if (count >= MAX_CONNECTIONS_PER_IP) {
|
|
ws.close(1008, 'Too many connections');
|
|
return;
|
|
}
|
|
|
|
connections.set(ip, count + 1);
|
|
|
|
ws.on('close', () => {
|
|
connections.set(ip, connections.get(ip) - 1);
|
|
});
|
|
});</code></pre>
|
|
<p><strong>Message Size Limits</strong>:</p>
|
|
<pre><code class="lang-javascript">const wss = new WebSocket.Server({
|
|
port: 8080,
|
|
maxPayload: 100 * 1024 // 100KB max message size
|
|
});</code></pre>
|
|
<p><strong>Compression Bomb Protection</strong>:</p>
|
|
<pre><code class="lang-javascript">const wss = new WebSocket.Server({
|
|
perMessageDeflate: {
|
|
zlibDeflateOptions: {
|
|
level: 6 // Balanced compression
|
|
},
|
|
zlibInflateOptions: {
|
|
chunkSize: 10 * 1024 // Limit decompressed chunks
|
|
},
|
|
threshold: 1024 // Only compress messages > 1KB
|
|
}
|
|
});</code></pre>
|
|
<hr>
|
|
<h2>Scaling Patterns</h2>
|
|
<h3>Horizontal Scaling Challenges</h3>
|
|
<p>WebSocket connections are stateful and long-lived, creating scaling challenges:</p>
|
|
<p><strong>Problem</strong>: Client connected to Server A cannot receive messages from Server B.</p>
|
|
<pre><code>Client 1 ─┬─> Server A ─┐
|
|
Client 2 ─┘ │
|
|
├─> Load Balancer
|
|
Client 3 ─┬─> Server B ─┘
|
|
Client 4 ─┘
|
|
|
|
If Client 1 sends to Client 3, message stuck in Server A.</code></pre>
|
|
<h3>Sticky Sessions</h3>
|
|
<p>Route all requests from a client to the same server.</p>
|
|
<p><strong>Load Balancer Configuration</strong> (Nginx):</p>
|
|
<pre><code class="lang-nginx">upstream websocket_backend {
|
|
ip_hash; # Route by client IP
|
|
server 10.0.0.1:8080;
|
|
server 10.0.0.2:8080;
|
|
server 10.0.0.3:8080;
|
|
}
|
|
|
|
server {
|
|
listen 80;
|
|
|
|
location /ws {
|
|
proxy_pass http://websocket_backend;
|
|
proxy_http_version 1.1;
|
|
proxy_set_header Upgrade $http_upgrade;
|
|
proxy_set_header Connection "Upgrade";
|
|
proxy_set_header Host $host;
|
|
proxy_set_header X-Real-IP $remote_addr;
|
|
}
|
|
}</code></pre>
|
|
<p><strong>HAProxy Configuration</strong>:</p>
|
|
<pre><code>frontend websocket_front
|
|
bind *:80
|
|
default_backend websocket_back
|
|
|
|
backend websocket_back
|
|
balance source # IP-based sticky sessions
|
|
server ws1 10.0.0.1:8080 check
|
|
server ws2 10.0.0.2:8080 check
|
|
server ws3 10.0.0.3:8080 check</code></pre>
|
|
<p><strong>Limitations</strong>:</p>
|
|
<ul><li>Uneven distribution if clients behind NAT</li><li>Can't rebalance without dropping connections</li><li>Server failure drops all its clients</li></ul>
|
|
<h3>Pub/Sub with Redis</h3>
|
|
<p>Enable cross-server messaging using Redis as a message broker.</p>
|
|
<p><strong>Architecture</strong>:</p>
|
|
<pre><code>Client 1 ──> Server A ──┐
|
|
├──> Redis Pub/Sub ──┬──> Server B ──> Client 3
|
|
Client 2 ──> Server B ──┘ └──> Server C ──> Client 4</code></pre>
|
|
<p><strong>Implementation</strong> (Node.js):</p>
|
|
<pre><code class="lang-javascript">const Redis = require('ioredis');
|
|
const WebSocket = require('ws');
|
|
|
|
// Create Redis clients (pub and sub must be separate)
|
|
const publisher = new Redis();
|
|
const subscriber = new Redis();
|
|
|
|
const wss = new WebSocket.Server({ port: 8080 });
|
|
|
|
// Subscribe to Redis channel
|
|
subscriber.subscribe('chat');
|
|
|
|
subscriber.on('message', (channel, message) => {
|
|
const msg = JSON.parse(message);
|
|
|
|
// Broadcast to all local WebSocket clients
|
|
wss.clients.forEach((client) => {
|
|
if (client.readyState === WebSocket.OPEN) {
|
|
// Optional: filter by room/topic
|
|
if (client.room === msg.room) {
|
|
client.send(JSON.stringify(msg));
|
|
}
|
|
}
|
|
});
|
|
});
|
|
|
|
// Handle WebSocket messages
|
|
wss.on('connection', (ws) => {
|
|
ws.on('message', (data) => {
|
|
const msg = JSON.parse(data);
|
|
|
|
// Publish to Redis (reaches all servers)
|
|
publisher.publish('chat', JSON.stringify(msg));
|
|
});
|
|
});</code></pre>
|
|
<p><strong>Room-Based Routing</strong>:</p>
|
|
<pre><code class="lang-javascript">// Client joins room
|
|
ws.on('message', (data) => {
|
|
const msg = JSON.parse(data);
|
|
|
|
if (msg.type === 'join') {
|
|
ws.room = msg.room;
|
|
subscriber.subscribe(`chat:${msg.room}`);
|
|
} else if (msg.type === 'message') {
|
|
publisher.publish(`chat:${ws.room}`, JSON.stringify(msg));
|
|
}
|
|
});
|
|
|
|
// Targeted broadcast
|
|
subscriber.on('message', (channel, message) => {
|
|
const room = channel.split(':')[1];
|
|
|
|
wss.clients.forEach((client) => {
|
|
if (client.room === room && client.readyState === WebSocket.OPEN) {
|
|
client.send(message);
|
|
}
|
|
});
|
|
});</code></pre>
|
|
<p><strong>Presence Tracking</strong>:</p>
|
|
<pre><code class="lang-javascript">const PRESENCE_KEY = 'websocket:presence';
|
|
|
|
wss.on('connection', (ws, req) => {
|
|
const userId = getUserId(req);
|
|
const serverId = process.env.SERVER_ID;
|
|
|
|
// Add to presence set
|
|
publisher.sadd(PRESENCE_KEY, JSON.stringify({
|
|
userId,
|
|
serverId,
|
|
connectedAt: Date.now()
|
|
}));
|
|
|
|
ws.on('close', () => {
|
|
// Remove from presence set
|
|
publisher.srem(PRESENCE_KEY, JSON.stringify({ userId, serverId }));
|
|
});
|
|
});
|
|
|
|
// Get online users
|
|
async function getOnlineUsers() {
|
|
const members = await publisher.smembers(PRESENCE_KEY);
|
|
return members.map(JSON.parse);
|
|
}</code></pre>
|
|
<h3>Redis Streams (Alternative)</h3>
|
|
<p>More robust than Pub/Sub with message persistence and consumer groups:</p>
|
|
<pre><code class="lang-javascript">const Redis = require('ioredis');
|
|
const redis = new Redis();
|
|
|
|
// Producer (WebSocket server receives message)
|
|
async function publishMessage(room, message) {
|
|
await redis.xadd(
|
|
`stream:${room}`,
|
|
'*', // Auto-generate ID
|
|
'data', JSON.stringify(message)
|
|
);
|
|
}
|
|
|
|
// Consumer (read messages)
|
|
async function consumeMessages(room) {
|
|
let lastId = '0-0';
|
|
|
|
while (true) {
|
|
const results = await redis.xread(
|
|
'BLOCK', 1000,
|
|
'STREAMS', `stream:${room}`, lastId
|
|
);
|
|
|
|
if (results) {
|
|
const [stream, messages] = results[0];
|
|
|
|
messages.forEach(([id, fields]) => {
|
|
const data = fields[1];
|
|
const msg = JSON.parse(data);
|
|
|
|
// Broadcast to WebSocket clients
|
|
broadcastToRoom(room, msg);
|
|
|
|
lastId = id;
|
|
});
|
|
}
|
|
}
|
|
}</code></pre>
|
|
<h3>Message Queue (RabbitMQ)</h3>
|
|
<p>For complex routing and guaranteed delivery:</p>
|
|
<pre><code class="lang-javascript">const amqp = require('amqplib');
|
|
|
|
async function setupRabbitMQ() {
|
|
const connection = await amqp.connect('amqp://localhost');
|
|
const channel = await connection.createChannel();
|
|
|
|
// Fanout exchange (broadcast to all)
|
|
await channel.assertExchange('websocket', 'fanout', { durable: false });
|
|
|
|
// Create queue for this server
|
|
const { queue } = await channel.assertQueue('', { exclusive: true });
|
|
await channel.bindQueue(queue, 'websocket', '');
|
|
|
|
// Consume messages
|
|
channel.consume(queue, (msg) => {
|
|
const data = JSON.parse(msg.content.toString());
|
|
|
|
wss.clients.forEach((client) => {
|
|
if (client.readyState === WebSocket.OPEN) {
|
|
client.send(JSON.stringify(data));
|
|
}
|
|
});
|
|
}, { noAck: true });
|
|
|
|
// Publish messages
|
|
wss.on('connection', (ws) => {
|
|
ws.on('message', (data) => {
|
|
channel.publish('websocket', '', Buffer.from(data));
|
|
});
|
|
});
|
|
}</code></pre>
|
|
<h3>Database for Persistence</h3>
|
|
<p>Store messages for offline users:</p>
|
|
<pre><code class="lang-javascript">const { Pool } = require('pg');
|
|
const pool = new Pool();
|
|
|
|
// Store message
|
|
async function storeMessage(roomId, userId, message) {
|
|
await pool.query(
|
|
'INSERT INTO messages (room_id, user_id, content, created_at) VALUES ($1, $2, $3, NOW())',
|
|
[roomId, userId, message]
|
|
);
|
|
}
|
|
|
|
// Get missed messages
|
|
async function getMissedMessages(roomId, since) {
|
|
const result = await pool.query(
|
|
'SELECT * FROM messages WHERE room_id = $1 AND created_at > $2 ORDER BY created_at',
|
|
[roomId, since]
|
|
);
|
|
return result.rows;
|
|
}
|
|
|
|
// On reconnection
|
|
ws.on('message', async (data) => {
|
|
const msg = JSON.parse(data);
|
|
|
|
if (msg.type === 'join') {
|
|
const missed = await getMissedMessages(msg.room, msg.lastSeen);
|
|
missed.forEach((m) => {
|
|
ws.send(JSON.stringify(m));
|
|
});
|
|
}
|
|
});</code></pre>
|
|
<h3>Serverless WebSocket</h3>
|
|
<p><strong>AWS API Gateway WebSockets</strong>:</p>
|
|
<pre><code class="lang-javascript">// Lambda handler for connect
|
|
exports.connect = async (event) => {
|
|
const connectionId = event.requestContext.connectionId;
|
|
|
|
// Store connection in DynamoDB
|
|
await dynamodb.put({
|
|
TableName: 'WebSocketConnections',
|
|
Item: { connectionId, timestamp: Date.now() }
|
|
}).promise();
|
|
|
|
return { statusCode: 200 };
|
|
};
|
|
|
|
// Lambda handler for message
|
|
exports.message = async (event) => {
|
|
const { connectionId } = event.requestContext;
|
|
const message = JSON.parse(event.body);
|
|
|
|
// Get all connections
|
|
const connections = await dynamodb.scan({
|
|
TableName: 'WebSocketConnections'
|
|
}).promise();
|
|
|
|
// Send to all
|
|
const apiGateway = new AWS.ApiGatewayManagementApi({
|
|
endpoint: event.requestContext.domainName + '/' + event.requestContext.stage
|
|
});
|
|
|
|
await Promise.all(connections.Items.map(async ({ connectionId: targetId }) => {
|
|
try {
|
|
await apiGateway.postToConnection({
|
|
ConnectionId: targetId,
|
|
Data: JSON.stringify(message)
|
|
}).promise();
|
|
} catch (e) {
|
|
if (e.statusCode === 410) {
|
|
// Clean up stale connection
|
|
await dynamodb.delete({
|
|
TableName: 'WebSocketConnections',
|
|
Key: { connectionId: targetId }
|
|
}).promise();
|
|
}
|
|
}
|
|
}));
|
|
|
|
return { statusCode: 200 };
|
|
};</code></pre>
|
|
<hr>
|
|
<h2>Reconnection Strategies</h2>
|
|
<p>Network interruptions require robust reconnection logic.</p>
|
|
<h3>Exponential Backoff</h3>
|
|
<p>Avoid overwhelming the server with reconnection attempts:</p>
|
|
<pre><code class="lang-javascript">class WebSocketClient {
|
|
constructor(url) {
|
|
this.url = url;
|
|
this.ws = null;
|
|
this.reconnectAttempts = 0;
|
|
this.maxReconnectAttempts = 10;
|
|
this.reconnectInterval = 1000; // Start at 1 second
|
|
this.maxReconnectInterval = 30000; // Cap at 30 seconds
|
|
}
|
|
|
|
connect() {
|
|
this.ws = new WebSocket(this.url);
|
|
|
|
this.ws.onopen = () => {
|
|
console.log('Connected');
|
|
this.reconnectAttempts = 0; // Reset on success
|
|
};
|
|
|
|
this.ws.onclose = (event) => {
|
|
console.log('Disconnected:', event.code, event.reason);
|
|
this.reconnect();
|
|
};
|
|
|
|
this.ws.onerror = (error) => {
|
|
console.error('Error:', error);
|
|
};
|
|
}
|
|
|
|
reconnect() {
|
|
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
console.error('Max reconnection attempts reached');
|
|
return;
|
|
}
|
|
|
|
this.reconnectAttempts++;
|
|
|
|
// Exponential backoff with jitter
|
|
const delay = Math.min(
|
|
this.reconnectInterval * Math.pow(2, this.reconnectAttempts),
|
|
this.maxReconnectInterval
|
|
);
|
|
|
|
const jitter = delay * 0.1 * Math.random(); // +/- 10% jitter
|
|
const actualDelay = delay + jitter;
|
|
|
|
console.log(`Reconnecting in ${actualDelay}ms (attempt ${this.reconnectAttempts})`);
|
|
|
|
setTimeout(() => {
|
|
this.connect();
|
|
}, actualDelay);
|
|
}
|
|
|
|
send(data) {
|
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
this.ws.send(data);
|
|
} else {
|
|
console.warn('Cannot send, not connected');
|
|
// Queue message or handle error
|
|
}
|
|
}
|
|
}
|
|
|
|
const client = new WebSocketClient('wss://api.example.com/ws');
|
|
client.connect();</code></pre>
|
|
<h3>Message Queueing</h3>
|
|
<p>Buffer messages while disconnected:</p>
|
|
<pre><code class="lang-javascript">class RobustWebSocket {
|
|
constructor(url) {
|
|
this.url = url;
|
|
this.ws = null;
|
|
this.messageQueue = [];
|
|
this.maxQueueSize = 100;
|
|
this.connect();
|
|
}
|
|
|
|
connect() {
|
|
this.ws = new WebSocket(this.url);
|
|
|
|
this.ws.onopen = () => {
|
|
console.log('Connected, flushing queue');
|
|
this.flushQueue();
|
|
};
|
|
|
|
this.ws.onclose = () => {
|
|
this.reconnect();
|
|
};
|
|
}
|
|
|
|
send(data) {
|
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
this.ws.send(data);
|
|
} else {
|
|
// Queue message
|
|
if (this.messageQueue.length < this.maxQueueSize) {
|
|
this.messageQueue.push(data);
|
|
} else {
|
|
console.warn('Message queue full, dropping oldest');
|
|
this.messageQueue.shift();
|
|
this.messageQueue.push(data);
|
|
}
|
|
}
|
|
}
|
|
|
|
flushQueue() {
|
|
while (this.messageQueue.length > 0 && this.ws.readyState === WebSocket.OPEN) {
|
|
const message = this.messageQueue.shift();
|
|
this.ws.send(message);
|
|
}
|
|
}
|
|
|
|
reconnect() {
|
|
// Exponential backoff logic from previous example
|
|
}
|
|
}</code></pre>
|
|
<h3>State Synchronization</h3>
|
|
<p>Resync state after reconnection:</p>
|
|
<pre><code class="lang-javascript">class StatefulWebSocket {
|
|
constructor(url) {
|
|
this.url = url;
|
|
this.ws = null;
|
|
this.lastMessageId = 0;
|
|
this.connect();
|
|
}
|
|
|
|
connect() {
|
|
this.ws = new WebSocket(this.url);
|
|
|
|
this.ws.onopen = () => {
|
|
// Request missed messages
|
|
this.ws.send(JSON.stringify({
|
|
type: 'sync',
|
|
lastMessageId: this.lastMessageId
|
|
}));
|
|
};
|
|
|
|
this.ws.onmessage = (event) => {
|
|
const msg = JSON.parse(event.data);
|
|
|
|
if (msg.id > this.lastMessageId) {
|
|
this.lastMessageId = msg.id;
|
|
this.handleMessage(msg);
|
|
} else {
|
|
// Duplicate or old message, ignore
|
|
}
|
|
};
|
|
}
|
|
|
|
handleMessage(msg) {
|
|
// Process message
|
|
console.log('Message:', msg);
|
|
}
|
|
}</code></pre>
|
|
<h3>Heartbeat Detection</h3>
|
|
<p>Detect connection death faster than TCP keepalive:</p>
|
|
<pre><code class="lang-javascript">class HeartbeatWebSocket {
|
|
constructor(url) {
|
|
this.url = url;
|
|
this.ws = null;
|
|
this.heartbeatInterval = null;
|
|
this.heartbeatTimeout = null;
|
|
this.HEARTBEAT_INTERVAL = 30000; // 30 seconds
|
|
this.HEARTBEAT_TIMEOUT = 5000; // 5 seconds
|
|
this.connect();
|
|
}
|
|
|
|
connect() {
|
|
this.ws = new WebSocket(this.url);
|
|
|
|
this.ws.onopen = () => {
|
|
this.startHeartbeat();
|
|
};
|
|
|
|
this.ws.onmessage = (event) => {
|
|
const msg = JSON.parse(event.data);
|
|
|
|
if (msg.type === 'pong') {
|
|
this.resetHeartbeat();
|
|
} else {
|
|
this.handleMessage(msg);
|
|
}
|
|
};
|
|
|
|
this.ws.onclose = () => {
|
|
this.stopHeartbeat();
|
|
this.reconnect();
|
|
};
|
|
}
|
|
|
|
startHeartbeat() {
|
|
this.heartbeatInterval = setInterval(() => {
|
|
this.ping();
|
|
}, this.HEARTBEAT_INTERVAL);
|
|
}
|
|
|
|
stopHeartbeat() {
|
|
if (this.heartbeatInterval) {
|
|
clearInterval(this.heartbeatInterval);
|
|
this.heartbeatInterval = null;
|
|
}
|
|
if (this.heartbeatTimeout) {
|
|
clearTimeout(this.heartbeatTimeout);
|
|
this.heartbeatTimeout = null;
|
|
}
|
|
}
|
|
|
|
ping() {
|
|
this.ws.send(JSON.stringify({ type: 'ping' }));
|
|
|
|
// Expect pong within timeout
|
|
this.heartbeatTimeout = setTimeout(() => {
|
|
console.warn('Heartbeat timeout, reconnecting');
|
|
this.ws.close();
|
|
}, this.HEARTBEAT_TIMEOUT);
|
|
}
|
|
|
|
resetHeartbeat() {
|
|
if (this.heartbeatTimeout) {
|
|
clearTimeout(this.heartbeatTimeout);
|
|
this.heartbeatTimeout = null;
|
|
}
|
|
}
|
|
|
|
reconnect() {
|
|
// Exponential backoff logic
|
|
}
|
|
}</code></pre>
|
|
<h3>Connection State Machine</h3>
|
|
<p>Robust state management:</p>
|
|
<pre><code class="lang-javascript">const States = {
|
|
DISCONNECTED: 'disconnected',
|
|
CONNECTING: 'connecting',
|
|
CONNECTED: 'connected',
|
|
RECONNECTING: 'reconnecting'
|
|
};
|
|
|
|
class StateMachineWebSocket {
|
|
constructor(url) {
|
|
this.url = url;
|
|
this.ws = null;
|
|
this.state = States.DISCONNECTED;
|
|
this.listeners = {};
|
|
}
|
|
|
|
connect() {
|
|
if (this.state !== States.DISCONNECTED) {
|
|
console.warn('Already connecting or connected');
|
|
return;
|
|
}
|
|
|
|
this.setState(States.CONNECTING);
|
|
this.ws = new WebSocket(this.url);
|
|
|
|
this.ws.onopen = () => {
|
|
this.setState(States.CONNECTED);
|
|
};
|
|
|
|
this.ws.onclose = () => {
|
|
if (this.state === States.CONNECTED) {
|
|
this.setState(States.RECONNECTING);
|
|
this.reconnect();
|
|
} else {
|
|
this.setState(States.DISCONNECTED);
|
|
}
|
|
};
|
|
|
|
this.ws.onerror = (error) => {
|
|
this.emit('error', error);
|
|
};
|
|
}
|
|
|
|
setState(newState) {
|
|
const oldState = this.state;
|
|
this.state = newState;
|
|
this.emit('stateChange', { from: oldState, to: newState });
|
|
}
|
|
|
|
on(event, callback) {
|
|
if (!this.listeners[event]) {
|
|
this.listeners[event] = [];
|
|
}
|
|
this.listeners[event].push(callback);
|
|
}
|
|
|
|
emit(event, data) {
|
|
if (this.listeners[event]) {
|
|
this.listeners[event].forEach(cb => cb(data));
|
|
}
|
|
}
|
|
|
|
reconnect() {
|
|
// Exponential backoff
|
|
setTimeout(() => {
|
|
this.state = States.DISCONNECTED;
|
|
this.connect();
|
|
}, 1000);
|
|
}
|
|
}
|
|
|
|
// Usage
|
|
const ws = new StateMachineWebSocket('wss://api.example.com/ws');
|
|
|
|
ws.on('stateChange', ({ from, to }) => {
|
|
console.log(`State: ${from} -> ${to}`);
|
|
|
|
if (to === States.CONNECTED) {
|
|
// Update UI to show connected
|
|
} else if (to === States.RECONNECTING) {
|
|
// Show reconnecting indicator
|
|
}
|
|
});
|
|
|
|
ws.connect();</code></pre>
|
|
<hr>
|
|
<h2>Server Implementations</h2>
|
|
<h3>Node.js (ws library)</h3>
|
|
<p><strong>Installation</strong>:</p>
|
|
<pre><code class="lang-bash">npm install ws</code></pre>
|
|
<p><strong>Basic Server</strong>:</p>
|
|
<pre><code class="lang-javascript">const WebSocket = require('ws');
|
|
|
|
const wss = new WebSocket.Server({ port: 8080 });
|
|
|
|
wss.on('connection', (ws, req) => {
|
|
console.log('Client connected:', req.socket.remoteAddress);
|
|
|
|
ws.on('message', (data, isBinary) => {
|
|
console.log('Received:', data.toString());
|
|
|
|
// Echo back
|
|
ws.send(data, { binary: isBinary });
|
|
});
|
|
|
|
ws.on('close', (code, reason) => {
|
|
console.log('Client disconnected:', code, reason.toString());
|
|
});
|
|
|
|
ws.on('error', (error) => {
|
|
console.error('WebSocket error:', error);
|
|
});
|
|
|
|
ws.send('Welcome!');
|
|
});
|
|
|
|
console.log('WebSocket server running on ws://localhost:8080');</code></pre>
|
|
<p><strong>Broadcast to All Clients</strong>:</p>
|
|
<pre><code class="lang-javascript">function broadcast(data) {
|
|
wss.clients.forEach((client) => {
|
|
if (client.readyState === WebSocket.OPEN) {
|
|
client.send(data);
|
|
}
|
|
});
|
|
}
|
|
|
|
wss.on('connection', (ws) => {
|
|
ws.on('message', (data) => {
|
|
broadcast(data); // Send to all connected clients
|
|
});
|
|
});</code></pre>
|
|
<p><strong>Room-Based Broadcasting</strong>:</p>
|
|
<pre><code class="lang-javascript">const rooms = new Map();
|
|
|
|
wss.on('connection', (ws) => {
|
|
ws.on('message', (data) => {
|
|
const msg = JSON.parse(data);
|
|
|
|
if (msg.type === 'join') {
|
|
if (!rooms.has(msg.room)) {
|
|
rooms.set(msg.room, new Set());
|
|
}
|
|
rooms.get(msg.room).add(ws);
|
|
ws.room = msg.room;
|
|
} else if (msg.type === 'message') {
|
|
const room = rooms.get(ws.room);
|
|
if (room) {
|
|
room.forEach((client) => {
|
|
if (client.readyState === WebSocket.OPEN) {
|
|
client.send(JSON.stringify(msg));
|
|
}
|
|
});
|
|
}
|
|
}
|
|
});
|
|
|
|
ws.on('close', () => {
|
|
if (ws.room && rooms.has(ws.room)) {
|
|
rooms.get(ws.room).delete(ws);
|
|
}
|
|
});
|
|
});</code></pre>
|
|
<p><strong>With Express</strong>:</p>
|
|
<pre><code class="lang-javascript">const express = require('express');
|
|
const { createServer } = require('http');
|
|
const WebSocket = require('ws');
|
|
|
|
const app = express();
|
|
const server = createServer(app);
|
|
const wss = new WebSocket.Server({ server });
|
|
|
|
app.get('/', (req, res) => {
|
|
res.send('WebSocket server running');
|
|
});
|
|
|
|
wss.on('connection', (ws) => {
|
|
ws.send('Connected to WebSocket server');
|
|
});
|
|
|
|
server.listen(8080, () => {
|
|
console.log('Server running on http://localhost:8080');
|
|
});</code></pre>
|
|
<p><strong>Compression (permessage-deflate)</strong>:</p>
|
|
<pre><code class="lang-javascript">const wss = new WebSocket.Server({
|
|
port: 8080,
|
|
perMessageDeflate: {
|
|
zlibDeflateOptions: {
|
|
chunkSize: 1024,
|
|
memLevel: 7,
|
|
level: 3
|
|
},
|
|
zlibInflateOptions: {
|
|
chunkSize: 10 * 1024
|
|
},
|
|
clientNoContextTakeover: true,
|
|
serverNoContextTakeover: true,
|
|
serverMaxWindowBits: 10,
|
|
concurrencyLimit: 10,
|
|
threshold: 1024 // Only compress messages > 1KB
|
|
}
|
|
});</code></pre>
|
|
<h3>Python (websockets library)</h3>
|
|
<p><strong>Installation</strong>:</p>
|
|
<pre><code class="lang-bash">pip install websockets</code></pre>
|
|
<p><strong>Basic Server</strong> (async):</p>
|
|
<pre><code class="lang-python">import asyncio
|
|
import websockets
|
|
|
|
async def handler(websocket, path):
|
|
print(f"Client connected: {websocket.remote_address}")
|
|
|
|
try:
|
|
async for message in websocket:
|
|
print(f"Received: {message}")
|
|
|
|
# Echo back
|
|
await websocket.send(message)
|
|
except websockets.exceptions.ConnectionClosed:
|
|
print("Client disconnected")
|
|
|
|
async def main():
|
|
async with websockets.serve(handler, "localhost", 8080):
|
|
print("WebSocket server running on ws://localhost:8080")
|
|
await asyncio.Future() # Run forever
|
|
|
|
asyncio.run(main())</code></pre>
|
|
<p><strong>Broadcast to All Clients</strong>:</p>
|
|
<pre><code class="lang-python">import asyncio
|
|
import websockets
|
|
|
|
connected = set()
|
|
|
|
async def handler(websocket, path):
|
|
connected.add(websocket)
|
|
try:
|
|
async for message in websocket:
|
|
# Broadcast to all clients
|
|
websockets.broadcast(connected, message)
|
|
finally:
|
|
connected.remove(websocket)
|
|
|
|
async def main():
|
|
async with websockets.serve(handler, "localhost", 8080):
|
|
await asyncio.Future()
|
|
|
|
asyncio.run(main())</code></pre>
|
|
<p><strong>JSON Messages</strong>:</p>
|
|
<pre><code class="lang-python">import asyncio
|
|
import websockets
|
|
import json
|
|
|
|
async def handler(websocket, path):
|
|
async for message in websocket:
|
|
data = json.loads(message)
|
|
|
|
# Process
|
|
response = {
|
|
"type": "response",
|
|
"echo": data
|
|
}
|
|
|
|
await websocket.send(json.dumps(response))
|
|
|
|
async def main():
|
|
async with websockets.serve(handler, "localhost", 8080):
|
|
await asyncio.Future()
|
|
|
|
asyncio.run(main())</code></pre>
|
|
<p><strong>With Authentication</strong>:</p>
|
|
<pre><code class="lang-python">import asyncio
|
|
import websockets
|
|
import jwt
|
|
|
|
async def handler(websocket, path):
|
|
# Read first message as auth token
|
|
try:
|
|
token = await asyncio.wait_for(websocket.recv(), timeout=5.0)
|
|
payload = jwt.decode(token, "secret", algorithms=["HS256"])
|
|
user_id = payload["user_id"]
|
|
except (asyncio.TimeoutError, jwt.InvalidTokenError):
|
|
await websocket.close(1008, "Authentication failed")
|
|
return
|
|
|
|
print(f"User {user_id} authenticated")
|
|
|
|
# Continue with authenticated connection
|
|
async for message in websocket:
|
|
await websocket.send(f"User {user_id}: {message}")
|
|
|
|
async def main():
|
|
async with websockets.serve(handler, "localhost", 8080):
|
|
await asyncio.Future()
|
|
|
|
asyncio.run(main())</code></pre>
|
|
<h3>Go (gorilla/websocket)</h3>
|
|
<p><strong>Installation</strong>:</p>
|
|
<pre><code class="lang-bash">go get github.com/gorilla/websocket</code></pre>
|
|
<p><strong>Basic Server</strong>:</p>
|
|
<pre><code class="lang-go">package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
var upgrader = websocket.Upgrader{
|
|
CheckOrigin: func(r *http.Request) bool {
|
|
return true // Allow all origins (configure for production)
|
|
},
|
|
}
|
|
|
|
func handler(w http.ResponseWriter, r *http.Request) {
|
|
conn, err := upgrader.Upgrade(w, r, nil)
|
|
if err != nil {
|
|
log.Println("Upgrade error:", err)
|
|
return
|
|
}
|
|
defer conn.Close()
|
|
|
|
fmt.Println("Client connected:", conn.RemoteAddr())
|
|
|
|
for {
|
|
messageType, message, err := conn.ReadMessage()
|
|
if err != nil {
|
|
log.Println("Read error:", err)
|
|
break
|
|
}
|
|
|
|
fmt.Printf("Received: %s\n", message)
|
|
|
|
// Echo back
|
|
err = conn.WriteMessage(messageType, message)
|
|
if err != nil {
|
|
log.Println("Write error:", err)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
http.HandleFunc("/ws", handler)
|
|
|
|
fmt.Println("WebSocket server running on :8080")
|
|
log.Fatal(http.ListenAndServe(":8080", nil))
|
|
}</code></pre>
|
|
<p><strong>Broadcast Hub</strong>:</p>
|
|
<pre><code class="lang-go">package main
|
|
|
|
import (
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
type Hub struct {
|
|
clients map[*websocket.Conn]bool
|
|
broadcast chan []byte
|
|
register chan *websocket.Conn
|
|
unregister chan *websocket.Conn
|
|
}
|
|
|
|
func newHub() *Hub {
|
|
return &Hub{
|
|
clients: make(map[*websocket.Conn]bool),
|
|
broadcast: make(chan []byte),
|
|
register: make(chan *websocket.Conn),
|
|
unregister: make(chan *websocket.Conn),
|
|
}
|
|
}
|
|
|
|
func (h *Hub) run() {
|
|
for {
|
|
select {
|
|
case conn := <-h.register:
|
|
h.clients[conn] = true
|
|
case conn := <-h.unregister:
|
|
if _, ok := h.clients[conn]; ok {
|
|
delete(h.clients, conn)
|
|
conn.Close()
|
|
}
|
|
case message := <-h.broadcast:
|
|
for conn := range h.clients {
|
|
err := conn.WriteMessage(websocket.TextMessage, message)
|
|
if err != nil {
|
|
h.unregister <- conn
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
var hub = newHub()
|
|
|
|
func handler(w http.ResponseWriter, r *http.Request) {
|
|
conn, _ := upgrader.Upgrade(w, r, nil)
|
|
hub.register <- conn
|
|
|
|
defer func() {
|
|
hub.unregister <- conn
|
|
}()
|
|
|
|
for {
|
|
_, message, err := conn.ReadMessage()
|
|
if err != nil {
|
|
break
|
|
}
|
|
hub.broadcast <- message
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
go hub.run()
|
|
|
|
http.HandleFunc("/ws", handler)
|
|
http.ListenAndServe(":8080", nil)
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>Client Implementations</h2>
|
|
<h3>Browser (Native WebSocket API)</h3>
|
|
<p><strong>Basic Connection</strong>:</p>
|
|
<pre><code class="lang-javascript">const ws = new WebSocket('wss://api.example.com/ws');
|
|
|
|
ws.onopen = (event) => {
|
|
console.log('Connected');
|
|
ws.send('Hello Server');
|
|
};
|
|
|
|
ws.onmessage = (event) => {
|
|
console.log('Received:', event.data);
|
|
|
|
// Parse JSON if needed
|
|
const data = JSON.parse(event.data);
|
|
};
|
|
|
|
ws.onerror = (error) => {
|
|
console.error('WebSocket error:', error);
|
|
};
|
|
|
|
ws.onclose = (event) => {
|
|
console.log('Disconnected:', event.code, event.reason);
|
|
};</code></pre>
|
|
<p><strong>Send Binary Data</strong>:</p>
|
|
<pre><code class="lang-javascript">// ArrayBuffer
|
|
const buffer = new ArrayBuffer(4);
|
|
const view = new DataView(buffer);
|
|
view.setUint32(0, 42);
|
|
ws.send(buffer);
|
|
|
|
// Blob
|
|
const blob = new Blob(['binary data']);
|
|
ws.send(blob);</code></pre>
|
|
<p><strong>Receive Binary Data</strong>:</p>
|
|
<pre><code class="lang-javascript">ws.binaryType = 'arraybuffer'; // or 'blob'
|
|
|
|
ws.onmessage = (event) => {
|
|
if (event.data instanceof ArrayBuffer) {
|
|
const view = new DataView(event.data);
|
|
const value = view.getUint32(0);
|
|
console.log('Binary:', value);
|
|
} else {
|
|
console.log('Text:', event.data);
|
|
}
|
|
};</code></pre>
|
|
<h3>Node.js Client (ws library)</h3>
|
|
<pre><code class="lang-javascript">const WebSocket = require('ws');
|
|
|
|
const ws = new WebSocket('wss://api.example.com/ws');
|
|
|
|
ws.on('open', () => {
|
|
console.log('Connected');
|
|
ws.send('Hello');
|
|
});
|
|
|
|
ws.on('message', (data, isBinary) => {
|
|
console.log('Received:', data.toString());
|
|
});
|
|
|
|
ws.on('close', (code, reason) => {
|
|
console.log('Closed:', code, reason.toString());
|
|
});
|
|
|
|
ws.on('error', (error) => {
|
|
console.error('Error:', error);
|
|
});</code></pre>
|
|
<h3>Python Client (websockets)</h3>
|
|
<pre><code class="lang-python">import asyncio
|
|
import websockets
|
|
|
|
async def client():
|
|
async with websockets.connect('wss://api.example.com/ws') as ws:
|
|
await ws.send('Hello')
|
|
|
|
async for message in ws:
|
|
print(f"Received: {message}")
|
|
|
|
asyncio.run(client())</code></pre>
|
|
<h3>React Hook (useWebSocket)</h3>
|
|
<pre><code class="lang-typescript">import { useEffect, useRef, useState } from 'react';
|
|
|
|
function useWebSocket(url: string) {
|
|
const [isConnected, setIsConnected] = useState(false);
|
|
const [lastMessage, setLastMessage] = useState<string | null>(null);
|
|
const ws = useRef<WebSocket | null>(null);
|
|
|
|
useEffect(() => {
|
|
ws.current = new WebSocket(url);
|
|
|
|
ws.current.onopen = () => {
|
|
setIsConnected(true);
|
|
};
|
|
|
|
ws.current.onmessage = (event) => {
|
|
setLastMessage(event.data);
|
|
};
|
|
|
|
ws.current.onclose = () => {
|
|
setIsConnected(false);
|
|
};
|
|
|
|
return () => {
|
|
ws.current?.close();
|
|
};
|
|
}, [url]);
|
|
|
|
const send = (data: string) => {
|
|
if (ws.current?.readyState === WebSocket.OPEN) {
|
|
ws.current.send(data);
|
|
}
|
|
};
|
|
|
|
return { isConnected, lastMessage, send };
|
|
}
|
|
|
|
// Usage
|
|
function App() {
|
|
const { isConnected, lastMessage, send } = useWebSocket('wss://api.example.com/ws');
|
|
|
|
return (
|
|
<div>
|
|
<p>Status: {isConnected ? 'Connected' : 'Disconnected'}</p>
|
|
<p>Last message: {lastMessage}</p>
|
|
<button onClick={() => send('Hello')}>Send</button>
|
|
</div>
|
|
);
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>Testing Strategies</h2>
|
|
<h3>Unit Testing</h3>
|
|
<p><strong>Test Message Handling</strong>:</p>
|
|
<pre><code class="lang-javascript">const WebSocket = require('ws');
|
|
|
|
describe('WebSocket Handler', () => {
|
|
let wss, ws;
|
|
|
|
beforeAll((done) => {
|
|
wss = new WebSocket.Server({ port: 8080 });
|
|
wss.on('connection', (socket) => {
|
|
socket.on('message', (data) => {
|
|
const msg = JSON.parse(data);
|
|
socket.send(JSON.stringify({ echo: msg }));
|
|
});
|
|
});
|
|
done();
|
|
});
|
|
|
|
afterAll(() => {
|
|
wss.close();
|
|
});
|
|
|
|
test('echoes message', (done) => {
|
|
ws = new WebSocket('ws://localhost:8080');
|
|
|
|
ws.on('open', () => {
|
|
ws.send(JSON.stringify({ test: 'data' }));
|
|
});
|
|
|
|
ws.on('message', (data) => {
|
|
const msg = JSON.parse(data);
|
|
expect(msg.echo.test).toBe('data');
|
|
ws.close();
|
|
done();
|
|
});
|
|
});
|
|
});</code></pre>
|
|
<h3>Integration Testing</h3>
|
|
<p><strong>Test Full Flow</strong>:</p>
|
|
<pre><code class="lang-javascript">describe('Chat Integration', () => {
|
|
let server, client1, client2;
|
|
|
|
beforeAll(async () => {
|
|
server = new WebSocket.Server({ port: 8080 });
|
|
// Setup broadcast logic
|
|
|
|
client1 = new WebSocket('ws://localhost:8080');
|
|
client2 = new WebSocket('ws://localhost:8080');
|
|
|
|
await Promise.all([
|
|
new Promise((resolve) => client1.on('open', resolve)),
|
|
new Promise((resolve) => client2.on('open', resolve))
|
|
]);
|
|
});
|
|
|
|
test('broadcasts message to all clients', (done) => {
|
|
client2.on('message', (data) => {
|
|
expect(data.toString()).toBe('Hello');
|
|
done();
|
|
});
|
|
|
|
client1.send('Hello');
|
|
});
|
|
|
|
afterAll(() => {
|
|
client1.close();
|
|
client2.close();
|
|
server.close();
|
|
});
|
|
});</code></pre>
|
|
<h3>Load Testing</h3>
|
|
<p><strong>Artillery</strong>:</p>
|
|
<pre><code class="lang-yaml"># artillery.yml
|
|
config:
|
|
target: "wss://api.example.com"
|
|
phases:
|
|
- duration: 60
|
|
arrivalRate: 10
|
|
name: "Warm up"
|
|
- duration: 120
|
|
arrivalRate: 50
|
|
name: "Sustained load"
|
|
engines:
|
|
ws:
|
|
timeout: 60
|
|
|
|
scenarios:
|
|
- engine: ws
|
|
flow:
|
|
- connect:
|
|
target: "/ws"
|
|
- send: '{"type": "join", "room": "test"}'
|
|
- think: 1
|
|
- loop:
|
|
- send: '{"type": "message", "text": "Hello"}'
|
|
- think: 2
|
|
count: 10</code></pre>
|
|
<pre><code class="lang-bash">artillery run artillery.yml</code></pre>
|
|
<p><strong>k6</strong>:</p>
|
|
<pre><code class="lang-javascript">import ws from 'k6/ws';
|
|
import { check } from 'k6';
|
|
|
|
export let options = {
|
|
vus: 100,
|
|
duration: '30s',
|
|
};
|
|
|
|
export default function () {
|
|
const url = 'wss://api.example.com/ws';
|
|
|
|
const res = ws.connect(url, {}, function (socket) {
|
|
socket.on('open', () => socket.send('Hello'));
|
|
|
|
socket.on('message', (data) => {
|
|
console.log('Received:', data);
|
|
});
|
|
|
|
socket.setTimeout(() => {
|
|
socket.close();
|
|
}, 10000);
|
|
});
|
|
|
|
check(res, { 'status is 101': (r) => r && r.status === 101 });
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>Common Patterns</h2>
|
|
<h3>Chat Application</h3>
|
|
<p><strong>Server</strong> (Node.js):</p>
|
|
<pre><code class="lang-javascript">const rooms = new Map();
|
|
|
|
wss.on('connection', (ws) => {
|
|
ws.on('message', (data) => {
|
|
const msg = JSON.parse(data);
|
|
|
|
switch (msg.type) {
|
|
case 'join':
|
|
if (!rooms.has(msg.room)) {
|
|
rooms.set(msg.room, new Set());
|
|
}
|
|
rooms.get(msg.room).add(ws);
|
|
ws.room = msg.room;
|
|
ws.username = msg.username;
|
|
break;
|
|
|
|
case 'message':
|
|
const room = rooms.get(ws.room);
|
|
if (room) {
|
|
const payload = JSON.stringify({
|
|
type: 'message',
|
|
username: ws.username,
|
|
text: msg.text,
|
|
timestamp: Date.now()
|
|
});
|
|
|
|
room.forEach((client) => {
|
|
if (client.readyState === WebSocket.OPEN) {
|
|
client.send(payload);
|
|
}
|
|
});
|
|
}
|
|
break;
|
|
}
|
|
});
|
|
|
|
ws.on('close', () => {
|
|
if (ws.room && rooms.has(ws.room)) {
|
|
rooms.get(ws.room).delete(ws);
|
|
}
|
|
});
|
|
});</code></pre>
|
|
<p><strong>Client</strong> (React):</p>
|
|
<pre><code class="lang-typescript">function Chat() {
|
|
const [messages, setMessages] = useState([]);
|
|
const [input, setInput] = useState('');
|
|
const ws = useRef<WebSocket>();
|
|
|
|
useEffect(() => {
|
|
ws.current = new WebSocket('wss://api.example.com/ws');
|
|
|
|
ws.current.onopen = () => {
|
|
ws.current.send(JSON.stringify({
|
|
type: 'join',
|
|
room: 'general',
|
|
username: 'Alice'
|
|
}));
|
|
};
|
|
|
|
ws.current.onmessage = (event) => {
|
|
const msg = JSON.parse(event.data);
|
|
setMessages((prev) => [...prev, msg]);
|
|
};
|
|
|
|
return () => ws.current?.close();
|
|
}, []);
|
|
|
|
const sendMessage = () => {
|
|
ws.current?.send(JSON.stringify({
|
|
type: 'message',
|
|
text: input
|
|
}));
|
|
setInput('');
|
|
};
|
|
|
|
return (
|
|
<div>
|
|
{messages.map((msg, i) => (
|
|
<div key={i}>{msg.username}: {msg.text}</div>
|
|
))}
|
|
<input value={input} onChange={(e) => setInput(e.target.value)} />
|
|
<button onClick={sendMessage}>Send</button>
|
|
</div>
|
|
);
|
|
}</code></pre>
|
|
<h3>Real-Time Dashboard</h3>
|
|
<p><strong>Server</strong> (push updates):</p>
|
|
<pre><code class="lang-javascript">const clients = new Set();
|
|
|
|
wss.on('connection', (ws) => {
|
|
clients.add(ws);
|
|
|
|
ws.on('close', () => {
|
|
clients.remove(ws);
|
|
});
|
|
});
|
|
|
|
// Push data updates
|
|
setInterval(() => {
|
|
const data = {
|
|
type: 'metrics',
|
|
cpu: Math.random() * 100,
|
|
memory: Math.random() * 100,
|
|
timestamp: Date.now()
|
|
};
|
|
|
|
clients.forEach((client) => {
|
|
if (client.readyState === WebSocket.OPEN) {
|
|
client.send(JSON.stringify(data));
|
|
}
|
|
});
|
|
}, 1000);</code></pre>
|
|
<p><strong>Client</strong> (React with Chart):</p>
|
|
<pre><code class="lang-typescript">function Dashboard() {
|
|
const [metrics, setMetrics] = useState([]);
|
|
|
|
useEffect(() => {
|
|
const ws = new WebSocket('wss://api.example.com/ws');
|
|
|
|
ws.onmessage = (event) => {
|
|
const data = JSON.parse(event.data);
|
|
setMetrics((prev) => [...prev.slice(-60), data]); // Keep last 60
|
|
};
|
|
|
|
return () => ws.close();
|
|
}, []);
|
|
|
|
return (
|
|
<LineChart data={metrics}>
|
|
<Line dataKey="cpu" stroke="#8884d8" />
|
|
<Line dataKey="memory" stroke="#82ca9d" />
|
|
</LineChart>
|
|
);
|
|
}</code></pre>
|
|
<h3>Multiplayer Game (State Sync)</h3>
|
|
<p><strong>Server</strong>:</p>
|
|
<pre><code class="lang-javascript">const gameState = {
|
|
players: new Map()
|
|
};
|
|
|
|
wss.on('connection', (ws) => {
|
|
const playerId = generateId();
|
|
|
|
gameState.players.set(playerId, {
|
|
id: playerId,
|
|
x: 0,
|
|
y: 0
|
|
});
|
|
|
|
// Send full state to new player
|
|
ws.send(JSON.stringify({
|
|
type: 'init',
|
|
playerId,
|
|
state: Array.from(gameState.players.values())
|
|
}));
|
|
|
|
// Broadcast new player to others
|
|
broadcast({
|
|
type: 'player_joined',
|
|
player: gameState.players.get(playerId)
|
|
});
|
|
|
|
ws.on('message', (data) => {
|
|
const msg = JSON.parse(data);
|
|
|
|
if (msg.type === 'move') {
|
|
const player = gameState.players.get(playerId);
|
|
player.x = msg.x;
|
|
player.y = msg.y;
|
|
|
|
// Broadcast position update
|
|
broadcast({
|
|
type: 'player_moved',
|
|
playerId,
|
|
x: msg.x,
|
|
y: msg.y
|
|
});
|
|
}
|
|
});
|
|
|
|
ws.on('close', () => {
|
|
gameState.players.delete(playerId);
|
|
broadcast({
|
|
type: 'player_left',
|
|
playerId
|
|
});
|
|
});
|
|
});</code></pre>
|
|
<hr>
|
|
<h2>Comparison with Alternatives</h2>
|
|
<h3>Server-Sent Events (SSE)</h3>
|
|
<p><strong>SSE Characteristics</strong>:</p>
|
|
<ul><li>Unidirectional (server → client only)</li><li>HTTP-based (simpler than WebSocket)</li><li>Automatic reconnection</li><li>Text-only (no binary)</li><li>EventSource API in browsers</li></ul>
|
|
<p><strong>When to Use SSE</strong>:</p>
|
|
<ul><li>One-way server push (notifications, live feeds)</li><li>Simpler infrastructure requirements</li><li>No binary data needed</li><li>Want automatic reconnection</li></ul>
|
|
<p><strong>When to Use WebSocket</strong>:</p>
|
|
<ul><li>Bidirectional communication needed</li><li>Low latency critical</li><li>Binary data</li><li>Custom protocols</li></ul>
|
|
<p><strong>SSE Example</strong>:</p>
|
|
<pre><code class="lang-javascript">// Server (Express)
|
|
app.get('/events', (req, res) => {
|
|
res.setHeader('Content-Type', 'text/event-stream');
|
|
res.setHeader('Cache-Control', 'no-cache');
|
|
res.setHeader('Connection', 'keep-alive');
|
|
|
|
const interval = setInterval(() => {
|
|
res.write(`data: ${JSON.stringify({ time: Date.now() })}\n\n`);
|
|
}, 1000);
|
|
|
|
req.on('close', () => {
|
|
clearInterval(interval);
|
|
});
|
|
});
|
|
|
|
// Client
|
|
const eventSource = new EventSource('/events');
|
|
|
|
eventSource.onmessage = (event) => {
|
|
const data = JSON.parse(event.data);
|
|
console.log(data);
|
|
};</code></pre>
|
|
<h3>Long Polling</h3>
|
|
<p><strong>Characteristics</strong>:</p>
|
|
<ul><li>Client repeatedly requests updates</li><li>Server holds request until data available</li><li>High overhead (new request each time)</li></ul>
|
|
<p><strong>When to Use Long Polling</strong>:</p>
|
|
<ul><li>Legacy browser support</li><li>Restrictive firewall/proxy</li><li>Very infrequent updates</li></ul>
|
|
<p><strong>When to Use WebSocket</strong>:</p>
|
|
<ul><li>Frequent updates</li><li>Modern browsers</li><li>Real-time requirements</li></ul>
|
|
<h3>HTTP/2 Server Push</h3>
|
|
<p><strong>Characteristics</strong>:</p>
|
|
<ul><li>Server can push resources proactively</li><li>Still request/response model</li><li>Limited browser support</li></ul>
|
|
<p><strong>WebSocket Advantages</strong>:</p>
|
|
<ul><li>True bidirectional</li><li>Lower overhead</li><li>Better browser support</li><li>Persistent connection</li></ul>
|
|
<hr>
|
|
<h2>Production Best Practices</h2>
|
|
<h3>Monitoring</h3>
|
|
<p><strong>Key Metrics</strong>:</p>
|
|
<ul><li>Active connections count</li><li>Message throughput (messages/sec)</li><li>Message latency (time from send to receive)</li><li>Connection duration</li><li>Reconnection rate</li><li>Error rate</li><li>Memory usage per connection</li></ul>
|
|
<p><strong>Prometheus Metrics</strong>:</p>
|
|
<pre><code class="lang-javascript">const prometheus = require('prom-client');
|
|
|
|
const activeConnections = new prometheus.Gauge({
|
|
name: 'websocket_connections_active',
|
|
help: 'Number of active WebSocket connections'
|
|
});
|
|
|
|
const messagesTotal = new prometheus.Counter({
|
|
name: 'websocket_messages_total',
|
|
help: 'Total number of WebSocket messages',
|
|
labelNames: ['direction', 'type']
|
|
});
|
|
|
|
const messageLatency = new prometheus.Histogram({
|
|
name: 'websocket_message_latency_seconds',
|
|
help: 'WebSocket message latency',
|
|
buckets: [0.001, 0.01, 0.1, 0.5, 1]
|
|
});
|
|
|
|
wss.on('connection', (ws) => {
|
|
activeConnections.inc();
|
|
|
|
ws.on('message', (data) => {
|
|
messagesTotal.inc({ direction: 'inbound', type: 'text' });
|
|
|
|
const start = Date.now();
|
|
// Process message
|
|
const duration = (Date.now() - start) / 1000;
|
|
messageLatency.observe(duration);
|
|
});
|
|
|
|
ws.on('close', () => {
|
|
activeConnections.dec();
|
|
});
|
|
});</code></pre>
|
|
<h3>Logging</h3>
|
|
<p><strong>Structured Logging</strong>:</p>
|
|
<pre><code class="lang-javascript">const winston = require('winston');
|
|
|
|
const logger = winston.createLogger({
|
|
format: winston.format.json(),
|
|
transports: [
|
|
new winston.transports.File({ filename: 'websocket.log' })
|
|
]
|
|
});
|
|
|
|
wss.on('connection', (ws, req) => {
|
|
const connId = generateId();
|
|
|
|
logger.info('connection', {
|
|
connId,
|
|
ip: req.socket.remoteAddress,
|
|
origin: req.headers.origin
|
|
});
|
|
|
|
ws.on('message', (data) => {
|
|
logger.debug('message', {
|
|
connId,
|
|
size: data.length,
|
|
type: typeof data
|
|
});
|
|
});
|
|
|
|
ws.on('close', (code, reason) => {
|
|
logger.info('disconnect', {
|
|
connId,
|
|
code,
|
|
reason: reason.toString()
|
|
});
|
|
});
|
|
|
|
ws.on('error', (error) => {
|
|
logger.error('error', {
|
|
connId,
|
|
error: error.message,
|
|
stack: error.stack
|
|
});
|
|
});
|
|
});</code></pre>
|
|
<h3>Resource Limits</h3>
|
|
<p><strong>Per-Connection Limits</strong>:</p>
|
|
<pre><code class="lang-javascript">const MAX_MESSAGE_SIZE = 100 * 1024; // 100KB
|
|
const MAX_MESSAGES_PER_MINUTE = 60;
|
|
|
|
const wss = new WebSocket.Server({
|
|
port: 8080,
|
|
maxPayload: MAX_MESSAGE_SIZE
|
|
});
|
|
|
|
const rateLimits = new WeakMap();
|
|
|
|
wss.on('connection', (ws) => {
|
|
rateLimits.set(ws, {
|
|
count: 0,
|
|
resetAt: Date.now() + 60000
|
|
});
|
|
|
|
ws.on('message', (data) => {
|
|
const limit = rateLimits.get(ws);
|
|
|
|
if (Date.now() > limit.resetAt) {
|
|
limit.count = 0;
|
|
limit.resetAt = Date.now() + 60000;
|
|
}
|
|
|
|
if (++limit.count > MAX_MESSAGES_PER_MINUTE) {
|
|
ws.close(1008, 'Rate limit exceeded');
|
|
return;
|
|
}
|
|
});
|
|
});</code></pre>
|
|
<h3>Graceful Shutdown</h3>
|
|
<pre><code class="lang-javascript">process.on('SIGTERM', () => {
|
|
console.log('SIGTERM received, closing connections');
|
|
|
|
wss.clients.forEach((ws) => {
|
|
ws.close(1001, 'Server shutting down');
|
|
});
|
|
|
|
const timeout = setTimeout(() => {
|
|
console.log('Force closing remaining connections');
|
|
wss.close(() => {
|
|
process.exit(0);
|
|
});
|
|
}, 30000);
|
|
|
|
wss.close(() => {
|
|
clearTimeout(timeout);
|
|
process.exit(0);
|
|
});
|
|
});</code></pre>
|
|
<hr>
|
|
<h2>Troubleshooting</h2>
|
|
<h3>Connection Fails</h3>
|
|
<p><strong>Check</strong>:</p>
|
|
<ol><li>Correct URL scheme (ws:// vs wss://)</li><li>Server is running and accessible</li><li>Firewall allows WebSocket connections</li><li>Load balancer configured for WebSocket upgrade</li><li>Certificate valid (for wss://)</li></ol>
|
|
<p><strong>Debug</strong>:</p>
|
|
<pre><code class="lang-javascript">ws.onerror = (error) => {
|
|
console.error('Connection error:', error);
|
|
// Check: incorrect URL, network issues, server down
|
|
};
|
|
|
|
ws.onclose = (event) => {
|
|
console.log('Close code:', event.code);
|
|
console.log('Close reason:', event.reason);
|
|
// 1006 = abnormal closure (network issue)
|
|
// 1011 = server error
|
|
};</code></pre>
|
|
<h3>Messages Not Received</h3>
|
|
<p><strong>Check</strong>:</p>
|
|
<ol><li>Connection state (OPEN)</li><li>Message size within limits</li><li>Proper masking (client→server)</li><li>Valid UTF-8 (text messages)</li><li>Server is broadcasting correctly</li></ol>
|
|
<p><strong>Debug</strong>:</p>
|
|
<pre><code class="lang-javascript">console.log('WebSocket state:', ws.readyState);
|
|
// 0 = CONNECTING, 1 = OPEN, 2 = CLOSING, 3 = CLOSED
|
|
|
|
if (ws.readyState === WebSocket.OPEN) {
|
|
ws.send('test');
|
|
} else {
|
|
console.warn('Cannot send, connection not open');
|
|
}</code></pre>
|
|
<h3>High Latency</h3>
|
|
<p><strong>Causes</strong>:</p>
|
|
<ul><li>Network congestion</li><li>Server overload</li><li>Message queue backlog</li><li>Slow message processing</li></ul>
|
|
<p><strong>Solutions</strong>:</p>
|
|
<pre><code class="lang-javascript">// Measure latency
|
|
ws.send(JSON.stringify({ type: 'ping', sent: Date.now() }));
|
|
|
|
ws.onmessage = (event) => {
|
|
const msg = JSON.parse(event.data);
|
|
if (msg.type === 'pong') {
|
|
const latency = Date.now() - msg.sent;
|
|
console.log('Latency:', latency, 'ms');
|
|
}
|
|
};
|
|
|
|
// Server-side processing time
|
|
const start = Date.now();
|
|
// ... process message ...
|
|
const duration = Date.now() - start;
|
|
if (duration > 100) {
|
|
console.warn('Slow processing:', duration, 'ms');
|
|
}</code></pre>
|
|
<h3>Memory Leaks</h3>
|
|
<p><strong>Common Causes</strong>:</p>
|
|
<ul><li>Not removing event listeners</li><li>Storing references to closed connections</li><li>Unbounded message buffers</li></ul>
|
|
<p><strong>Prevention</strong>:</p>
|
|
<pre><code class="lang-javascript">const clients = new Set();
|
|
|
|
wss.on('connection', (ws) => {
|
|
clients.add(ws);
|
|
|
|
ws.on('close', () => {
|
|
clients.delete(ws); // Clean up reference
|
|
});
|
|
});
|
|
|
|
// Use WeakMap for connection metadata
|
|
const metadata = new WeakMap();
|
|
|
|
wss.on('connection', (ws) => {
|
|
metadata.set(ws, { /* data */ }); // Auto-cleaned when ws GC'd
|
|
});</code></pre>
|
|
<hr>
|
|
<h2>Performance Optimization</h2>
|
|
<h3>Compression</h3>
|
|
<p>Enable permessage-deflate for text messages:</p>
|
|
<pre><code class="lang-javascript">const wss = new WebSocket.Server({
|
|
perMessageDeflate: {
|
|
threshold: 1024 // Only compress > 1KB
|
|
}
|
|
});</code></pre>
|
|
<p><strong>Trade-offs</strong>:</p>
|
|
<ul><li>CPU usage vs bandwidth</li><li>Latency increase (compression time)</li><li>Memory usage (compression contexts)</li></ul>
|
|
<h3>Binary Protocols</h3>
|
|
<p>Use binary formats for structured data:</p>
|
|
<p><strong>MessagePack</strong>:</p>
|
|
<pre><code class="lang-javascript">const msgpack = require('msgpack-lite');
|
|
|
|
// Send
|
|
const data = { user: 'Alice', count: 42 };
|
|
const encoded = msgpack.encode(data);
|
|
ws.send(encoded, { binary: true });
|
|
|
|
// Receive
|
|
ws.on('message', (data, isBinary) => {
|
|
if (isBinary) {
|
|
const decoded = msgpack.decode(data);
|
|
}
|
|
});</code></pre>
|
|
<p><strong>Protocol Buffers</strong>:</p>
|
|
<pre><code class="lang-protobuf">message ChatMessage {
|
|
string username = 1;
|
|
string text = 2;
|
|
int64 timestamp = 3;
|
|
}</code></pre>
|
|
<pre><code class="lang-javascript">const protobuf = require('protobufjs');
|
|
|
|
const root = protobuf.loadSync('chat.proto');
|
|
const ChatMessage = root.lookupType('ChatMessage');
|
|
|
|
// Send
|
|
const message = ChatMessage.create({
|
|
username: 'Alice',
|
|
text: 'Hello',
|
|
timestamp: Date.now()
|
|
});
|
|
const buffer = ChatMessage.encode(message).finish();
|
|
ws.send(buffer, { binary: true });</code></pre>
|
|
<h3>Batching</h3>
|
|
<p>Reduce overhead by batching multiple messages:</p>
|
|
<pre><code class="lang-javascript">const batch = [];
|
|
const BATCH_SIZE = 10;
|
|
const BATCH_INTERVAL = 100; // ms
|
|
|
|
function queueMessage(msg) {
|
|
batch.push(msg);
|
|
|
|
if (batch.length >= BATCH_SIZE) {
|
|
flushBatch();
|
|
}
|
|
}
|
|
|
|
function flushBatch() {
|
|
if (batch.length === 0) return;
|
|
|
|
ws.send(JSON.stringify(batch));
|
|
batch.length = 0;
|
|
}
|
|
|
|
setInterval(flushBatch, BATCH_INTERVAL);</code></pre>
|
|
<h3>Connection Pooling (Client)</h3>
|
|
<p>Reuse connections for multiple logical channels:</p>
|
|
<pre><code class="lang-javascript">class WebSocketPool {
|
|
constructor(url, size) {
|
|
this.connections = [];
|
|
for (let i = 0; i < size; i++) {
|
|
this.connections.push(new WebSocket(url));
|
|
}
|
|
this.index = 0;
|
|
}
|
|
|
|
getConnection() {
|
|
const conn = this.connections[this.index];
|
|
this.index = (this.index + 1) % this.connections.length;
|
|
return conn;
|
|
}
|
|
|
|
send(data) {
|
|
const conn = this.getConnection();
|
|
if (conn.readyState === WebSocket.OPEN) {
|
|
conn.send(data);
|
|
}
|
|
}
|
|
}
|
|
|
|
const pool = new WebSocketPool('wss://api.example.com/ws', 5);
|
|
pool.send('message 1');
|
|
pool.send('message 2');</code></pre>
|
|
<hr>
|
|
<p><strong>End of WebSocket Reference</strong></p>
|
|
<p>This comprehensive reference covers the WebSocket protocol from fundamentals to production deployment. For hands-on examples, see the <code>examples/</code> directory. For testing and analysis tools, see the <code>scripts/</code> directory.</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="/reference.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |