6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.jsのhttp.ServerでUNIXドメインソケットを使う

Last updated at Posted at 2019-09-24

本稿ではNode.jsのビルトインモジュールhttpを使い、UNIXドメインソケットをリッスンするHTTPサーバの立て方を説明する。サンプルコードにはTypeScriptを用いる。

本稿のゴール

Node.jsのhttp.ServerでUNIXドメインソケットを使ったHTTPサーバを立て、そのサーバとHTTPで話してみる。

http.Serverでドメインソケットを使う

ドメインソケットをリッスンするHTTPサーバの立て方の実装例を示す。

import http, {IncomingMessage, ServerResponse} from 'http'
import fs from 'fs';

const socketFile = '/tmp/http.sock'

fs.existsSync(socketFile) && fs.unlinkSync(socketFile) // ソケットファイルがあるとHTTPサーバが起動しないため

// HTTPサーバ
http.createServer((req: IncomingMessage, res: ServerResponse): void => {
    res.write('Hello!')
    res.end()
}).listen(socketFile)

ポイントとしては、listen関数にポート番号を与えるのではなく、ソケットファイルのファイルパスを与えること。与えられたファイルパスにファイルがあるとHTTPサーバは起動しない。そのため、listenを呼び出す前にソケットファイルが無いことを確認しておく必要がある。

ドメインソケット越しにHTTPサーバと話す

ドメインソケットを通じて、HTTPサーバにリクエストを送ってみる。ここではncコマンドを使う。

echo -e "GET / HTTP/1.1\nHost:localhost\n" | nc -U /tmp/http.sock

出力結果

HTTP/1.1 200 OK
Date: Tue, 24 Sep 2019 09:56:25 GMT
Connection: keep-alive
Transfer-Encoding: chunked

6
Hello!
0

HTTPサーバからのレスポンスが表示される。

参考文献

6
5
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
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?