From 8cb4c3556b2de453b2da62035ebb761b92cbced1 Mon Sep 17 00:00:00 2001 From: Andrew Haynes Date: Sun, 1 Nov 2026 23:46:01 -0500 Subject: [PATCH] checkpoint 2: websocket echo + test page --- index.ts | 34 +++++++++++++++++++++++++--------- ws-test.html | 24 ++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 9 deletions(-) create mode 100644 ws-test.html diff --git a/index.ts b/index.ts index 77bf31d..9d0d971 100644 --- a/index.ts +++ b/index.ts @@ -18,6 +18,12 @@ const pages: Record = { "/trading": "trading.html", "/ws-test": "ws-test.html", }; + +async function serveFile(path: string): Promise { + const file = Bun.file(path); + if (await file.exists()) return new Response(file); + return new Response("Not Found", { status: 404 }); +} const server = Bun.serve({ port: 3000, async fetch(req, server) { @@ -32,13 +38,7 @@ const server = Bun.serve({ } const page = pages[url.pathname]; - if (page) { - const file = Bun.file(page); - if (!(await file.exists())) { - return new Response("Not Found", { status: 404 }); - } - return new Response(Bun.file(page)); - } + if (page) return serveFile(page); if ( url.pathname.startsWith("/client/") || @@ -47,7 +47,7 @@ const server = Bun.serve({ if (url.pathname.includes("..")) { return new Response("Bad path", { status: 400 }); } - return new Response(Bun.file("." + url.pathname)); + return serveFile("." + url.pathname); } if (url.pathname === "/styles.css") @@ -66,7 +66,23 @@ const server = Bun.serve({ console.log("A client connect via websocket!"); }, message(ws, message) { - const data = JSON.parse(message as string); + const text = typeof message === "string" ? message : message.toString(); + console.log("recv:", text); + + let data: any; + try { + data = JSON.parse(text); + } catch { + ws.send(JSON.stringify({ type: "ERROR", messsage: "Invalid JSON" })); + return; + } + + if (data.type === "ECHO") { + ws.send(JSON.stringify({ type: "ECHO", text: data.text })); + return; + } + + // const data = JSON.parse(message as string); if (data.type === "CREATE_ROOM") { const roomCode = Math.floor(1000 + Math.random() * 9000).toString(); diff --git a/ws-test.html b/ws-test.html new file mode 100644 index 0000000..507b999 --- /dev/null +++ b/ws-test.html @@ -0,0 +1,24 @@ + + +WebSocket test + +

+
+