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 ではサポートされていません。onMessageonCloseonError
注意
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 appts
// 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 },
})