websockets
This commit is contained in:
parent
d7a96baa4b
commit
84c182a17d
|
|
@ -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')
|
||||
}
|
||||
|
|
@ -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
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user