# 即時串流

除了 Webhook 之外，你也可以透過 **WebSocket** 建立一條長連線，即時接收事件推送。當你需要持續、低延遲的串流（而非逐筆 HTTP 回呼）時，這是更合適的選擇。

## 連線

端點為 `GET /v1/stream`，升級為 WebSocket。連線需通過 API key 認證——在升級請求的 header 帶上 `X-API-Key`。

{% tabs %}
{% tab title="JavaScript" %}

```javascript
// 以支援自訂 header 的 WebSocket client 為例
const ws = new WebSocket("wss://api.atlantis.example/v1/stream", {
  headers: { "X-API-Key": "ak_live_YOUR_KEY" },
});

ws.on("message", (data) => {
  console.log("event:", data.toString());
});
```

{% endtab %}

{% tab title="Python" %}

```python
import websocket

ws = websocket.create_connection(
    "wss://api.atlantis.example/v1/stream",
    header=["X-API-Key: ak_live_YOUR_KEY"],
)
print(ws.recv())  # welcome 訊息
```

{% endtab %}
{% endtabs %}

## 連線後的訊息

連線建立後，伺服器會先送一則 **welcome** 訊息，確認連線與身分：

```json
{ "type": "welcome", "key": "ak_live_3f9a2c7b" }
```

之後，符合你訂閱條件的事件會以 JSON 訊息推送到這條連線上。

## 保持連線

* 送出文字訊息 `ping`，伺服器會回 `pong`，可用於保活與偵測斷線。
* 收到 `Close` 或連線中斷時，請以退避策略重新連線。

{% hint style="info" %}
WebSocket 與 Webhook 可擇一或併用：Webhook 適合無狀態、可水平擴展的接收端；WebSocket 適合需要持續低延遲串流的場景。
{% endhint %}

## 下一步

{% content-ref url="/pages/rZvbLNrM5PeNxP5udFDV" %}
[管理後台](/documentation/cao-zuo-zhi-nan/admin-console.md)
{% endcontent-ref %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.blockchainsecurity.asia/documentation/cao-zuo-zhi-nan/streaming.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
