LoginSignup
10
3

More than 3 years have passed since last update.

Node.jsでWebSocketサーバをUnixドメインソケットで立てる

Last updated at Posted at 2019-10-24

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.
> てすと
< てすと
>

参考文献

10
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
3