Skip to content

WebSocket 助手

🌐 WebSocket Helper

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

🌐 WebSocket Helper is a helper for server-side WebSockets in Hono applications. Currently Cloudflare Workers / Pages, Deno, Bun, and Node.js adapters are available.

导入

🌐 Import

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()

🌐 On Node.js, WebSocket support is built into @hono/node-server. To enable it, install ws and, if you use TypeScript, @types/ws. Then create a WebSocketServer with { noServer: true } and pass it to serve() via the websocket option.

@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')
      },
    }
  })
)

可用事件:

🌐 Available events:

  • onOpen - 目前,Cloudflare Workers 不支持它。
  • onMessage
  • onClose
  • onError

WARNING

如果你在使用 WebSocket Helper 的路由上使用修改头的中间件(例如,应用 CORS),你可能会遇到一个错误,提示你不能修改不可变的头。这是因为 upgradeWebSocket() 也会在内部更改头信息。

🌐 If you use middleware that modifies headers (e.g., applying CORS) on a route that uses WebSocket Helper, you may encounter an error saying you can't modify immutable headers. This is because upgradeWebSocket() also changes headers internally.

因此,如果你同时使用 WebSocket Helper 和中间件,请谨慎使用。

🌐 Therefore, please be cautious if you are using WebSocket Helper and middleware at the same time.

RPC 模式

🌐 RPC-mode

使用 WebSocket Helper 定义的处理程序支持 RPC 模式。

🌐 Handlers defined with WebSocket Helper support RPC mode.

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

示例

🌐 Examples

查看使用 WebSocket Helper 的示例。

🌐 See the examples using WebSocket Helper.

服务器和客户端

🌐 Server and Client

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)
})

带有 JSX 的 Bun

🌐 Bun with 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 },
})

Hono 中文网 - 粤ICP备13048890号