// A node:http server with ws's WebSocketServer on /live. It greets every client when // one connects, echoes text and binary, and answers a few commands that exercise the // protocol: a fragmented message, a ping, large frames, a server close and a crash. import http from "node:http"; import { readFileSync } from "node:fs"; import { WebSocketServer } from "ws"; const FILES = { "/": ["index.html", "text/html; charset=utf-8"], "/client.js": ["client.js", "text/javascript; charset=utf-8"], "/app.js": ["app.js", "text/javascript; charset=utf-8"], }; const server = http.createServer((req, res) => { const file = FILES[new URL(req.url, "http://localhost").pathname]; if (!file) { res.writeHead(404, { "content-type": "text/plain" }).end("not found"); return; } res.writeHead(200, { "content-type": file[1] }).end(readFileSync(`public/${file[0]}`)); }); const pattern = (n) => Buffer.from(Array.from({ length: n }, (_, i) => i & 255)); const sum = (bytes) => bytes.reduce((a, b) => (a + b) % 65521, 0); const wss = new WebSocketServer({ server, path: "/live", handleProtocols: (offered) => (offered.has("echo") ? "echo" : false) }); wss.on("connection", (ws) => { for (const client of wss.clients) client.send(`welcome ${wss.clients.size}`); ws.on("pong", (data) => ws.send(`pong:${data}`)); ws.on("message", (data, isBinary) => { if (isBinary) { ws.send(data.length > 125 ? `got:${data.length}:${sum(data)}` : data); return; } const text = String(data); if (text === "close-me") ws.close(4000, "asked to close"); else if (text === "fragment") { ws.send("frag-", { fin: false }); ws.send("ment", { fin: true }); } else if (text === "ping") ws.ping("p"); else if (text.startsWith("big:")) ws.send(pattern(Number(text.slice(4)))); else if (text === "shutdown") server.close(); else if (text === "crash") { setImmediate(() => { throw new Error("crash requested"); }); } else ws.send(`echo:${text}`); }); }); server.listen(3000, () => console.log("listening on 3000"));