websockets

This commit is contained in:
Chris Wanstrath 2025-09-19 14:59:17 -07:00
parent d7a96baa4b
commit 84c182a17d
2 changed files with 40 additions and 2 deletions

View File

@ -1,3 +1,23 @@
let ws: WebSocket | null = null
// open our websocket connection
export function startConnection() { 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')
} }

View File

@ -1,5 +1,5 @@
import { Hono } from "hono" import { Hono } from "hono"
import { serveStatic } from "hono/bun" import { serveStatic, upgradeWebSocket, websocket } from "hono/bun"
import { prettyJSON } from "hono/pretty-json" import { prettyJSON } from "hono/pretty-json"
import color from "kleur" 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 // app routes
// //
@ -117,4 +134,5 @@ export default {
hostname: "0.0.0.0", hostname: "0.0.0.0",
fetch: app.fetch, fetch: app.fetch,
idleTimeout: 0, idleTimeout: 0,
websocket
} }