跳转到正文

WebSocket 辅助工具 ​

WebSocket 辅助工具用于 Hono 应用中的服务器端 WebSocket。 目前提供 Cloudflare Workers / Pages、Deno、Bun 和 Node.js 适配器。

导入 ​

各运行时适配器都是独立的软件包(@hono/cloudflare-workers、@hono/deno、@hono/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 { upgradeWebSocket, websocket } from '@hono/bun'

// ...

export default {
  fetch: app.fetch,
  websocket,
}
ts
import { serve, upgradeWebSocket } from '@hono/node-server'
import { Hono } from 'hono'
import { WebSocketServer } from 'ws'

在 Node.js 上,WebSocket 支持内置于 @hono/node-server。要启用它,请安装 ws;使用 TypeScript 时还需安装 @types/ws。然后使用 { noServer: true } 创建 WebSocketServer,通过 websocket 选项传给 serve()。

@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>('http://localhost: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>('http://localhost: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 { upgradeWebSocket, websocket } from '@hono/bun'
import { html } from 'hono/html'

const app = new Hono()

app.get('/', (c) => {
  return c.html(
    <html>
      <head>
        <meta charset='UTF-8' />
      </head>
      <body>
        <div id='now-time'></div>
        {html`
          <script>
            const ws = new WebSocket('ws://localhost: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,
}

Node.js ​

ts
import { serve, upgradeWebSocket } from '@hono/node-server'
import { Hono } from 'hono'
import { WebSocketServer } from 'ws'

const app = new Hono()

app.get(
  '/ws',
  upgradeWebSocket(() => ({
    onMessage(event, ws) {
      ws.send(event.data)
    },
  }))
)

const wss = new WebSocketServer({ noServer: true })

serve({
  fetch: app.fetch,
  websocket: { server: wss },
})

基于 MIT 许可证发布。