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

# 实时流

> 通过 Server-Sent Events (SSE) 流订阅实时应用事件。

`app.realtime()` 会打开一个 [Server-Sent Events](https://developer.mozilla.org/docs/Web/API/Server-sent_events) 流并返回原始的 `Response`。SDK **不会**替你解析 SSE 帧，而是把流交给你，让你接入自己的事件循环。

## 连接限制

* 每个连接最多持续 **10 分钟**，之后服务器会关闭它
* 单个账户最多可同时保持 **10 个并发连接**

## 事件结构

该流发出两类帧：

* `event: system` — 连接生命周期消息，例如 `REALTIME_CONNECTING`、`REALTIME_TIMEOUT` 等
* `event: message` — JSON 应用负载

## 消费流

```typescript theme={null}
import { SquareCloudAPI } from "@squarecloud/api";

const api = new SquareCloudAPI(process.env.SQUARE_API_KEY!);
const app = await api.applications.fetch("abc123def456abc123def456");

const response = await app.realtime();

if (!response.body) {
    throw new Error("No stream body");
}

const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";

while (true) {
    const { value, done } = await reader.read();
    if (done) break;

    buffer += value;

    // SSE frames are separated by \n\n
    let separator = buffer.indexOf("\n\n");
    while (separator !== -1) {
        const rawFrame = buffer.slice(0, separator);
        buffer = buffer.slice(separator + 2);
        separator = buffer.indexOf("\n\n");

        const event = parseSSE(rawFrame);
        if (!event) continue;

        if (event.name === "system") {
            console.log(`[system] ${event.data}`);
            continue;
        }

        try {
            const payload = JSON.parse(event.data);
            console.log("[message]", payload);
        } catch {
            console.log("[message]", event.data);
        }
    }
}

function parseSSE(frame: string): { name: string; data: string } | null {
    let name = "message";
    let data = "";

    for (const line of frame.split("\n")) {
        if (line.startsWith("event:")) name = line.slice(6).trim();
        else if (line.startsWith("data:")) data += line.slice(5).trim();
    }

    return data ? { name, data } : null;
}
```

<Tip>
  每次调用 `app.realtime()` 都会返回一个全新的 `Response`。若要在 10 分钟的服务器超时之后保持连接，请在流结束时重新连接。
</Tip>
