WebSocket 助手
WebSocket 助手是 Hono 应用程序中服务器端 WebSockets 的助手。目前,Cloudflare Workers / Pages、Deno 和 Bun 适配器可用。
导入
ts
import { Hono } from 'hono'
import { upgradeWebSocket } from 'hono/cloudflare-workers'
ts
import { Hono } from 'hono'
import { upgradeWebSocket } from 'hono/deno'
ts
import { Hono } from 'hono'
import { createBunWebSocket } from 'hono/bun'
import type { ServerWebSocket } from 'bun'
const { upgradeWebSocket, websocket } =
createBunWebSocket<ServerWebSocket>()
// ...
export default {
fetch: app.fetch,
websocket,
}
如果您使用 Node.js,您可以使用 @hono/node-ws.
upgradeWebSocket()
upgradeWebSocket()
返回一个处理 WebSocket 的句柄。
ts
const app = new Hono()
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')
},
}
})
)
可用事件
onOpen
- 目前,Cloudflare Workers 不支持它。onMessage
onClose
onError
警告
如果您在使用 WebSocket 助手的路由上使用修改标头的中间件(例如,应用 CORS),您可能会遇到一个错误,指出您无法修改不可变标头。这是因为 upgradeWebSocket()
在内部也会更改标头。
因此,如果您同时使用 WebSocket 助手和中间件,请务必谨慎。
RPC 模式
使用 WebSocket 助手定义的句柄支持 RPC 模式。
ts
// server.ts
const wsApp = app.get(
'/ws',
upgradeWebSocket((c) => {
//...
})
)
export type WebSocketApp = typeof wsApp
// client.ts
const client = hc<WebSocketApp>('https://127.0.0.1:8787')
const socket = client.ws.$ws() // A WebSocket object for a client
示例
查看使用 WebSocket 助手的示例。
服务器和客户端
ts
// server.ts
import { Hono } from 'hono'
import { upgradeWebSocket } from 'hono/cloudflare-workers'
const app = new Hono().get(
'/ws',
upgradeWebSocket(() => {
return {
onMessage: (event) => {
console.log(event.data)
},
}
})
)
export default app
ts
// client.ts
import { hc } from 'hono/client'
import type app from './server'
const client = hc<typeof app>('https://127.0.0.1:8787')
const ws = client.ws.$ws(0)
ws.addEventListener('open', () => {
setInterval(() => {
ws.send(new Date().toString())
}, 1000)
})
Bun 与 JSX
tsx
import { Hono } from 'hono'
import { createBunWebSocket } from 'hono/bun'
const { upgradeWebSocket, websocket } = createBunWebSocket()
const app = new Hono()
app.get('/', (c) => {
return c.html(
<html>
<head>
<meta charset='UTF-8' />
</head>
<body>
<div id='now-time'></div>
<script
dangerouslySetInnerHTML={{
__html: `
const ws = new WebSocket('ws://127.0.0.1:3000/ws')
const $nowTime = document.getElementById('now-time')
ws.onmessage = (event) => {
$nowTime.textContent = event.data
}
`,
}}
></script>
</body>
</html>
)
})
const ws = app.get(
'/ws',
upgradeWebSocket((c) => {
let intervalId
return {
onOpen(_event, ws) {
intervalId = setInterval(() => {
ws.send(new Date().toString())
}, 200)
},
onClose() {
clearInterval(intervalId)
},
}
})
)
export default {
fetch: app.fetch,
websocket,
}