> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Laravel Reverb

> 為 Laravel 應用程式提供即時 WebSocket 通訊的官方伺服器套件

<Info>
  本頁專注於 Reverb 伺服器本身的安裝與運行。
  關於 broadcast 事件的建立與 Laravel Echo 的使用方式，請參閱 [Broadcasting](/zh-TW/broadcasting)。
</Info>

## 什麼是 Reverb

[Laravel Reverb](https://github.com/laravel/reverb) 是 Laravel 官方提供的自我託管 WebSocket 伺服器。
可在不依賴外部服務的情況下，為 Laravel 應用程式加入高速且可擴展的即時通訊。

Reverb 運行於 [broadcasting](/zh-TW/broadcasting) 之上，負責將伺服器端事件透過 WebSocket 送達瀏覽器。

```mermaid theme={null}
flowchart LR
    A["瀏覽器<br>Laravel Echo"] -->|"WebSocket 連線"| B["Laravel Reverb<br>伺服器"]
    B -->|"授權、路由"| C["Channel<br>管理"]
    C -->|"事件送出"| A
    D["Laravel 應用<br>觸發事件"] -->|"broadcast<br>（經由 queue）"| B
```

## 安裝

使用 `install:broadcasting` Artisan 指令，可一次安裝 Reverb 與所有相依。

```shell theme={null}
php artisan install:broadcasting
```

執行指令時選擇 Reverb，或加上 `--reverb` 選項執行，即可自動安裝 Reverb。

```shell theme={null}
php artisan install:broadcasting --reverb
```

此指令會執行以下事項：

* 安裝 Composer 套件（`laravel/reverb`）
* 安裝 NPM 套件（`laravel-echo`、`pusher-js`）
* 於 `.env` 加入環境變數
* 產生 `config/reverb.php`

若手動安裝，先以 Composer 加入套件，再執行 `reverb:install`。

```shell theme={null}
composer require laravel/reverb
php artisan reverb:install
```

## 設定

### 應用程式認證資訊

以環境變數設定用戶端與伺服器建立連線時所用的認證資訊。

```ini theme={null}
REVERB_APP_ID=my-app-id
REVERB_APP_KEY=my-app-key
REVERB_APP_SECRET=my-app-secret
```

這些值會在 `config/reverb.php` 的 `apps` 區段中被參照。

### 允許的來源（Allowed Origins）

可透過 `config/reverb.php` 的 `allowed_origins` 限制允許哪些來源提出用戶端請求。

```php theme={null}
'apps' => [
    [
        'app_id' => 'my-app-id',
        'allowed_origins' => ['laravel.com'],
        // ...
    ]
]
```

允許所有來源時指定 `*`。

### 多應用支援

一台 Reverb 伺服器可支援多個應用程式。
在 `config/reverb.php` 的 `apps` 陣列加入多個項目。

```php theme={null}
'apps' => [
    [
        'app_id' => 'my-app-one',
        // ...
    ],
    [
        'app_id' => 'my-app-two',
        // ...
    ],
],
```

### SSL 設定

正式環境中，通常由 Nginx 等 Web 伺服器負責 SSL 終端，並將請求 proxy 至 Reverb。
若想在本機開發環境使用 Secure WebSocket（`wss://`），可利用 Laravel Herd 或 Valet 的憑證。

```shell theme={null}
php artisan reverb:start --host="0.0.0.0" --port=8080 --hostname="laravel.test"
```

若要手動指定憑證，可在 `config/reverb.php` 設定 `tls` 選項。

```php theme={null}
'options' => [
    'tls' => [
        'local_cert' => '/path/to/cert.pem'
    ],
],
```

## 啟動伺服器

以 `reverb:start` Artisan 指令啟動伺服器。

```shell theme={null}
php artisan reverb:start
```

預設會在 `0.0.0.0:8080` 啟動。
可用 `--host` / `--port` 選項指定自訂位址。

```shell theme={null}
php artisan reverb:start --host=127.0.0.1 --port=9000
```

也可以用環境變數指定。

```ini theme={null}
REVERB_SERVER_HOST=0.0.0.0
REVERB_SERVER_PORT=8080
```

<Info>
  `REVERB_SERVER_HOST` / `REVERB_SERVER_PORT` 為伺服器本身的監聽位址。
  `REVERB_HOST` / `REVERB_PORT` 為 Laravel 應用送出 broadcast 訊息時的目的地。
  正式環境中兩者可能不同。
</Info>

### Debug 模式

為了效能，Reverb 預設不輸出除錯資訊。
若要觀察連線或訊息流程，可使用 `--debug` 選項。

```shell theme={null}
php artisan reverb:start --debug
```

### 重啟伺服器

Reverb 是常駐 process，要反映程式碼變更需重啟。
`reverb:restart` 指令會 graceful 結束所有連線後停止伺服器。

```shell theme={null}
php artisan reverb:restart
```

若使用 Supervisor 等 process manager，停止後會自動重啟。

## 監控

Reverb 支援與 [Laravel Pulse](https://laravel.com/docs/pulse) 整合。
可將連線數與訊息數即時顯示於儀表板。

首先在 `config/pulse.php` 加入 Reverb 的 recorder。

```php theme={null}
use Laravel\Reverb\Pulse\Recorders\ReverbConnections;
use Laravel\Reverb\Pulse\Recorders\ReverbMessages;

'recorders' => [
    ReverbConnections::class => [
        'sample_rate' => 1,
    ],

    ReverbMessages::class => [
        'sample_rate' => 1,
    ],

    // ...
],
```

接著在 Pulse 儀表板的樣板加入卡片。

```blade theme={null}
<x-pulse>
    <livewire:reverb.connections cols="full" />
    <livewire:reverb.messages cols="full" />
    ...
</x-pulse>
```

為了正確記錄連線狀況，請在 Reverb 伺服器上啟動 `pulse:check` daemon。
若為橫向擴展架構，`pulse:check` 只在一台伺服器執行。

## 在正式環境運行

### 檔案開啟上限

一個 WebSocket 連線會消耗一個 file descriptor。
請確認 OS 層級的限制，並視需要提高上限。

```shell theme={null}
ulimit -n
```

可在 `/etc/security/limits.conf` 變更上限。

```ini theme={null}
# /etc/security/limits.conf
forge        soft  nofile  10000
forge        hard  nofile  10000
```

### Event Loop（ext-uv）

Reverb 預設使用 PHP 的 `stream_select`，此方法有最多 1,024 個檔案的限制。
若要處理 1,000 個以上的同時連線，可安裝 `ext-uv` 解除限制。

```shell theme={null}
pecl install uv
```

`ext-uv` 可用時，Reverb 會自動改用它。

### Nginx 反向代理

正式環境不直接曝露 Reverb，而是透過 Nginx 等 Web 伺服器代理。
以下為 Nginx 的設定範例。

```nginx theme={null}
server {
    ...

    location / {
        proxy_http_version 1.1;
        proxy_set_header Host $http_host;
        proxy_set_header Scheme $scheme;
        proxy_set_header SERVER_PORT $server_port;
        proxy_set_header REMOTE_ADDR $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";

        proxy_pass http://0.0.0.0:8080;
    }

    ...
}
```

<Warning>
  Reverb 於 `/app` 接受 WebSocket 連線、於 `/apps` 接受 API 請求。
  請在 Web 伺服器設定中允許存取這兩個 URI。
</Warning>

要提升同時連線數，可調整 `nginx.conf` 的 `worker_rlimit_nofile` 與 `worker_connections`。

```nginx theme={null}
user forge;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
worker_rlimit_nofile 10000;

events {
  worker_connections 10000;
  multi_accept on;
}
```

### Process 管理（Supervisor）

正式環境中以 Supervisor 管理 Reverb process。
設定 `supervisor.conf` 的 `minfds` 以確保所需的 file descriptor。

```ini theme={null}
[supervisord]
...
minfds=10000
```

Supervisor 設定範例：

```ini theme={null}
[program:reverb]
process_name=%(program_name)s
command=php /path/to/artisan reverb:start
autostart=true
autorestart=true
user=forge
redirect_stderr=true
stdout_logfile=/path/to/reverb.log
```

### 擴展（Redis）

當單一伺服器無法處理所需的連線數時，可利用 Redis 的 pub/sub 功能進行橫向擴展。

```mermaid theme={null}
flowchart TB
    LB["Load Balancer"] --> R1["Reverb 伺服器 1"]
    LB --> R2["Reverb 伺服器 2"]
    LB --> R3["Reverb 伺服器 3"]
    R1 <-->|"pub/sub"| Redis["Redis"]
    R2 <-->|"pub/sub"| Redis
    R3 <-->|"pub/sub"| Redis
```

於 `.env` 啟用擴展。

```env theme={null}
REVERB_SCALING_ENABLED=true
```

Reverb 會使用應用程式預設的 Redis 連線在伺服器之間交換訊息。
啟動多台 Reverb 伺服器，並用 load balancer 分派請求。

<Info>
  [Laravel Cloud](https://cloud.laravel.com) 提供不需管理基礎架構就能部署 Reverb 應用的
  fully managed WebSocket 基礎架構。
</Info>

## 事件

Reverb 在連線與訊息的生命週期中會發出以下事件。
可透過 [事件監聽器](/zh-TW/events) 接收並加入自訂處理。

| 事件                 | 說明                        |
| ------------------ | ------------------------- |
| `ChannelCreated`   | 建立 channel 時（第一個連線訂閱時）    |
| `ChannelRemoved`   | 刪除 channel 時（最後一個連線取消訂閱時） |
| `ConnectionPruned` | 舊連線被伺服器切斷時                |
| `MessageReceived`  | 收到來自用戶端訊息時                |
| `MessageSent`      | 送出訊息至用戶端時                 |

這些事件皆位於 `Laravel\Reverb\Events` 命名空間。

## 後續步驟

<Card title="Broadcasting" href="/zh-TW/broadcasting">
  確認 broadcast 事件的建立、channel 授權與 Laravel Echo 的設定方式
</Card>

<Card title="事件與 Listener" href="/zh-TW/events">
  學習用來接收 Reverb 所發出事件的 Laravel 事件系統
</Card>


## Related topics

- [廣播](/zh-TW/broadcasting.md)
- [Laravel 11 以後的新應用程式結構 FAQ](/zh-TW/advanced/app-structure-faq.md)
- [部署](/zh-TW/deployment.md)
- [Laravel Cloud — Laravel 專用 PaaS 全貌](/zh-TW/blog/laravel-cloud.md)
- [2026 年 3 月 Laravel 更新](/zh-TW/blog/changelog/202603.md)
