跳至內容

WebSocket 輔助工具

WebSocket 輔助工具是 Hono 應用程式中用於伺服器端 WebSocket 的輔助工具。目前 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,
}

以 MIT 許可發佈。