Node.jsでwsパッケージのWebSocketサーバをUnixドメインソケットでlistenする方法です。サンプルコードはTypeScriptです。
Unixドメインソケットを使ったWebSocketサーバを立てるコード
Serverクラスのコンストラクタのserver
オプションにhttp.Server
のインスタンスを渡すのがミソです。
server.ts
import websocket from 'ws'
import http from 'http'
import fs from 'fs'
// UnixドメインソケットでWebSocketを待ち受けるHTTPサーバー
const hs: http.Server = http.createServer()
// WebSocketサーバー (いわゆるechoサーバーです)
const wss = new websocket.Server({server: hs}) // 最重要
wss.on('connection', ws => {
ws.send('hello, this is websocket echo server.')
ws.on('message', message => {
ws.send(message) // オウム返し
})
})
// Unixドメインソケットのファイル名
const socketPath = '/tmp/server.sock'
// UnixドメインソケットのファイルがあるとHTTPサーバが起動しないので必ず削除する
fs.existsSync(socketPath) && fs.unlinkSync(socketPath)
// HTTPサーバのlistenを開始する
hs.listen(socketPath, () => {
console.log(`websocket server listening on ${socketPath}`)
})
WebSocketサーバーと話してみる
WebSocketサーバと話すには、wscatというWebSocket CLIクライアントが便利です。
Unixドメインソケットではない、普通のTCPのWebSocketと疎通するには、npx wscat -c ws://echo.websocket.org
のように、URLをws://
で始めますが、Unixドメインソケットでは、URLスキーマの部分がws+unix://
になります:
$ npx wscat -c ws+unix:///tmp/server.sock
Connected (press CTRL+C to quit)
< hello, this is websocket echo server.
> てすと
< てすと
>