---
title: "TCPの接続を許可する"
language: "ja"
documentation_version: "3.x"
channel: "development"
release_context: null
source_revision: "10297d1e28653321d6996609fc53718d3b7c8278"
working_tree_clean: true
source_path: "docs/ja/guides/tcp.md"
source_sha256: "55138531559fab8234bbb6b04010bc2ba9a135a862cc4cf0a1965d5cf5bd9a56"
source_at_revision: true
source_url: "https://github.com/matsumotory/ngx_mruby/blob/10297d1e28653321d6996609fc53718d3b7c8278/docs/ja/guides/tcp.md"
html_url: "https://ngx.mruby.org/ja/guides/tcp/"
markdown_url: "https://ngx.mruby.org/markdown/ja/guides/tcp.md"
last_updated: "2026-10-29"
---

# TCPの接続を許可する

streamモジュールは、TCPの接続をプロキシし、`listen ... udp`ではUDPのセッションもプロキシします。`stream`ブロックの`server`では、[`mruby_stream`](/ja/reference/directives/#stream-module-directives)で指定したRubyのスクリプトが、streamモジュールのaccessフェーズで動きます。スクリプトは、nginxがupstreamに接続する前に、セッションごとに1回動きます。スクリプトは`Nginx::Stream::Connection`でセッションのアドレスを読みます。スクリプトが`stream_status`を`Nginx::Stream::ABORT`にすると、セッションが閉じます。

## サンプル

スクリプトは、リストにあるアドレスからのセッションだけを通します。その後、nginxは接続をupstreamへプロキシします。ここでのupstreamは、テストの設定にあるポート18168のHTTPのサーバです。リクエストとレスポンスは、クライアントがTCPの接続で送るバイト列と受け取るバイト列です。

```nginx title="test/conf/conf.d/stream/42-guide-tcp.conf"
upstream guide_tcp_backend {
    server 127.0.0.1:18168;
}

server {
    listen 127.0.0.1:12364;
    mruby_stream build/nginx/html/guide_tcp.rb;
    proxy_pass guide_tcp_backend;
}
```

```ruby title="test/html/guide_tcp.rb"
allowed = ["127.0.0.1", "::1"]
c = Nginx::Stream::Connection
c.stream_status = Nginx::Stream::ABORT unless allowed.include?(c.remote_ip)
```

```http title="test/html/guide_tcp.request：ケースが送るリクエスト"
GET /status HTTP/1.1
Host: 127.0.0.1:12364
Connection: close
```

```http title="test/html/guide_tcp.response：ケースが比べるレスポンス"
HTTP/1.1 200 OK
Content-Type: text/plain

the backend on port 18168 answered
```

<p class="caption sample-caption">CIが動くたびに、ケースの<code>test/t/cases/guides.rb</code>がこのリクエストを送ります。ケースは、ステータス行、ここに載せたヘッダ、ボディ全体を比べます。<span class="nowrap">5個</span>のファイルを最後に変えたのは、<span class="nowrap">2026-10-29</span>のコミット<span class="nowrap"><code>32219e53</code>です。</span></p>

## 気をつけること

- streamモジュールは、UDPのセッションでもスクリプトを実行します。テストスイートが送るのはTCPだけです。
- スクリプトはnginxがクライアントのデータを読む前に動くので、判断に使えるのは、クライアントが送る内容ではなく、セッションのアドレスとポートです。
- `stream`ブロックは、`http`ブロックとは別に独自の`mrb_state`を持ちます。起動時に動くコードにも、`stream`ブロック専用のディレクティブの`mruby_stream_init`と`mruby_stream_init_worker`があります。
