diff --git a/src/js/websocket.ts b/src/js/websocket.ts index c81e13e..4f75eee 100644 --- a/src/js/websocket.ts +++ b/src/js/websocket.ts @@ -1,3 +1,23 @@ +let ws: WebSocket | null = null + +// open our websocket connection export function startConnection() { - console.log("whee") + const url = new URL('/ws', location.href) + url.protocol = url.protocol.replace('http', 'ws') + ws = new WebSocket(url) + + ws.onopen = () => console.log('WS connected') + ws.onmessage = e => console.log('WS message:', e.data) + ws.onclose = () => setTimeout(startConnection, 1000) // simple retry + ws.onerror = () => ws?.close() +} + +// send any message +export function send(obj: any) { + ws?.readyState === 1 && ws.send(JSON.stringify(obj)) +} + +// close it... plz don't do this, though +export function close() { + ws?.close(1000, 'bye') } \ No newline at end of file diff --git a/src/server.tsx b/src/server.tsx index 992fa29..81e85fa 100644 --- a/src/server.tsx +++ b/src/server.tsx @@ -1,5 +1,5 @@ import { Hono } from "hono" -import { serveStatic } from "hono/bun" +import { serveStatic, upgradeWebSocket, websocket } from "hono/bun" import { prettyJSON } from "hono/pretty-json" import color from "kleur" @@ -42,6 +42,23 @@ app.get("/js/:path{.+}", async c => { } }) +// +// websocket +// + +app.get("/ws", upgradeWebSocket((c) => { + return { + onMessage(event, ws) { + console.log(`Message from client: ${event.data}`) + ws.send('Hello from server!') + }, + onClose: () => { + console.log('Connection closed') + }, + } +}) +) + // // app routes // @@ -117,4 +134,5 @@ export default { hostname: "0.0.0.0", fetch: app.fetch, idleTimeout: 0, + websocket } \ No newline at end of file