# 服务器发送事件

服务器发送事件（Server-sent events，SSE）是一项 Web 标准，允许 HTTP 服务器通过一条长连接向浏览器推送文本消息，并经 `EventSource` 接口以 DOM 事件的形式交付给页面脚本。其传输格式使用 `text/event-stream` MIME 类型，该规范现作为 WHATWG HTML 标准第 9.2 节维护。<sup>[1](https://html.spec.whatwg.org/multipage/server-sent-events.html)</sup>

| 关键事实 | 详情 |
|---|---|
| 方向 | 单向：数据仅从服务器流向客户端；客户端不能通过同一连接发送消息<sup>[2](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)</sup> |
| 传输格式 | `text/event-stream` MIME 类型下形如 `field: value` 的文本行；字段为 `data`（必需）、`event`、`id` 和 `retry`；空行终止每条消息<sup>[3](https://www.rfc-editor.org/rfc/rfc8895.html)</sup> |
| 重连 | 连接关闭时客户端自动重连；HTTP 204 No Content 响应告知客户端停止重连<sup>[1](https://html.spec.whatwg.org/multipage/server-sent-events.html)</sup> |
| 续传支持 | 重连时，客户端在 `Last-Event-ID` HTTP 请求头中发送最后收到的事件 ID<sup>[4](https://html.spec.whatwg.org/multipage/comms.html)</sup> |
| 连接状态 | `readyState` 为 `CONNECTING`（0）、`OPEN`（1）或 `CLOSED`（2）<sup>[2](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)</sup> |
| 编码 | 事件流始终按 UTF-8 解码；不能指定其他字符编码<sup>[1](https://html.spec.whatwg.org/multipage/server-sent-events.html)</sup> |
| 连接数限制 | 不使用 HTTP/2 时，浏览器将每个浏览器与每个域名的 SSE 连接数限制在约 6 条；使用 HTTP/2 时，协商的默认值为 100 条并发流<sup>[2](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)</sup> |
| 浏览器支持 | Firefox 6+、Safari 5+、Chrome 6+；自 2020 年 1 月起在各浏览器中广泛可用<sup>[2](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)</sup> |

## 目的及其在推送技术中的位置

传统上，网页必须请求数据才能收到数据。服务器发送事件将这一点反转：服务器可以随时向页面推送新数据，页面则将收到的消息视为带数据的事件。<sup>[5](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events)</sup> 与 WebSocket 不同，SSE 是单向的，从服务器到客户端，因此适合社交媒体状态更新、新闻推送，或将数据交付到 [IndexedDB](https://www.edgepedia.org/zh/indexeddb) 等客户端存储中。<sup>[2](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)</sup>

规范作者还主张使用原生 API，而不是用 `XMLHttpRequest` 或 `iframe` 来模拟：知道某条连接是事件流的用户代理可以与网络运营商协调，更好地利用网络资源，从而显著延长便携设备的电池续航时间。<sup>[1](https://html.spec.whatwg.org/multipage/server-sent-events.html)</sup>

## 事件流格式

该格式是一种刻意保持极简、按行分隔的文本协议。<sup>[6](https://www.server-sent-events.com/sse-protocol-fundamentals-architecture/understanding-the-event-stream-format/)</sup> 每一行的形式为 `field-name: value`。以冒号开头的行是注释，客户端会忽略；不含冒号的行也会被忽略。一条消息由空行终止，即连续两个行终止符。<sup>[3](https://www.rfc-editor.org/rfc/rfc8895.html)</sup>

协议定义了四个字段名：

- `data`：事件载荷，为文本形式。一条消息中的多个 `data` 行以换行符拼接，多行消息即以此方式书写。<sup>[3](https://www.rfc-editor.org/rfc/rfc8895.html)</sup>
- `event`：设置客户端派发的事件类型。默认类型为 `message`。<sup>[1](https://html.spec.whatwg.org/multipage/server-sent-events.html)</sup>
- `id`：设置最后事件 ID 字符串，用于断开后恢复。<sup>[3](https://www.rfc-editor.org/rfc/rfc8895.html)</sup>
- `retry`：设置重连时间，单位为毫秒，即客户端重连前等待的时长。<sup>[7](https://jakarta.ee/specifications/restful-ws/3.0/jakarta-restful-ws-spec-3.0.pdf)</sup>

包含两种事件类型的流如下所示：<sup>[1](https://html.spec.whatwg.org/multipage/server-sent-events.html)</sup>

```
event: add
data: 73857293

event: remove
data: 2153
```

派发消息时，事件的 `type` 属性设为 `message`，除非 `event` 字段给出了其他类型；其 `data` 属性保存累积的数据；其 origin 为流经过重定向后的最终 URL 的 origin；其 `lastEventId` 属性保存最后事件 ID 字符串。如果后续事件没有 `id` 字段，其 `lastEventId` 仍报告所见的最后一个 ID。<sup>[1](https://html.spec.whatwg.org/multipage/server-sent-events.html)</sup>

## EventSource 接口

客户端代码用流的 URL 创建 `EventSource` 并注册监听器：<sup>[1](https://html.spec.whatwg.org/multipage/server-sent-events.html)</sup>

```js
const source = new EventSource('updates.cgi');
source.onmessage = (event) => {
  console.log(event.data);
};
```

命名事件通过为服务器发送的每种类型调用 `addEventListener` 来接收；`message` 监听器既能捕获没有 `event` 字段的事件，也能捕获显式标注为 `message` 类型的事件。<sup>[2](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)</sup> 对于跨源流，构造函数接受一个选项字典，其中 `withCredentials: true` 会将连接请求的凭据模式设为 `include`。<sup>[1](https://html.spec.whatwg.org/multipage/server-sent-events.html)</sup>

该接口暴露只读的 `url`、`readyState` 和 `withCredentials` 属性，`close()` 方法，以及 `onopen`、`onmessage` 和 `onerror` 处理器。调用 `close()` 会关闭连接并将 `readyState` 设为 `CLOSED`；如果连接已经关闭，则不做任何事。<sup>[2](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)</sup> 该接口在 Web Worker 中同样可用。<sup>[5](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events)</sup>

## 重连与恢复

连接丢失时，用户代理将 `readyState` 设为 `CONNECTING`，触发 `error` 事件，等待重连时间（由实现定义的值，可能在数秒左右），然后重新连接。用户代理可能会在尝试失败后加入指数退避，以避免给不堪重负的服务器增加负担，或者等待操作系统通知网络连接已恢复。<sup>[1](https://html.spec.whatwg.org/multipage/server-sent-events.html)</sup>

重连时，如果最后事件 ID 字符串非空，客户端会在 `Last-Event-ID` 请求头中发送它，使服务器知道流中断的位置，从而重发或跳过遗漏的事件。<sup>[4](https://html.spec.whatwg.org/multipage/comms.html)</sup> 希望客户端停止重连的服务器以 HTTP 204 No Content 响应；连接以此方式失败后，用户代理不再尝试重连。<sup>[1](https://html.spec.whatwg.org/multipage/server-sent-events.html)</sup> 事件流请求可以像普通 HTTP 请求一样通过 [HTTP 301](https://www.edgepedia.org/zh/http-301) 和 307 重定向进行重定向。<sup>[1](https://html.spec.whatwg.org/multipage/server-sent-events.html)</sup>

规范未定义服务器如何告知客户端因断开时间过长而丢失了缓冲事件。2022 年一项为此添加响应头的提案被 WHATWG 编辑拒绝，他们建议通过 SSE 协议本身的消息来传达此类状态；一位编辑指出，该特性未被广泛扩展，因为它可以在用户层基于 `fetch` 实现。<sup>[8](https://github.com/whatwg/html/issues/8297)</sup>

## 运维注意事项

**连接数限制。** 在 HTTP/1.1 上，一条 SSE 连接占用浏览器每域名允许的约六条并行连接之一，因此打开多个标签页可能耗尽配额；该问题在 Chrome 和 Firefox 中已被标记为“不予修复”。在 [HTTP/2](https://www.edgepedia.org/zh/http-2) 上，流在一条连接上多路复用，并发流限制由客户端与服务器协商，默认为 100。<sup>[2](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)</sup>

**保持连接存活。** 中间设备可能丢弃空闲的 HTTP 连接。如 SSE 规范所建议，RFC 8895 建议更新流服务器每 15 秒发送一行注释或一个事件，以防客户端和代理丢弃连接；注释行被客户端忽略，但能保持流量流动。<sup>[3](https://www.rfc-editor.org/rfc/rfc8895.html)</sup>

**关闭时无客户端到服务器的信号。** `EventSource.close()` 只是关闭 HTTP 连接，并不通知服务器。为每个客户端保留发射器的服务器框架只有在写入失败时才会得知关闭；2018 年 WHATWG 的一次讨论将此归类为服务器端问题，因为 HTTP/1 除了关闭连接外无法发出客户端关闭的信号。<sup>[9](https://github.com/whatwg/html/issues/3380)</sup>

**安全。** `Last-Event-ID` 头的值可以包含除 CR 和 LF 之外的任意字节，且由于重连请求会跟随重定向，配合的服务器可以导致该头被发送到另一个 origin；2017 年 Fetch 规范的一次讨论指出了这一长期存在的行为。<sup>[10](https://github.com/whatwg/fetch/issues/568)</sup>

## 历史与标准化

该规范最初是 W3C 的 HTML5 的一部分。首份工作草案于 2009 年 4 月 23 日发布，草案于 2009 年 12 月进入最后征求意见阶段，服务器发送事件于 2015 年 2 月 3 日成为 W3C 推荐标准。W3C 于 2021 年 1 月 28 日废止其版本，该规范现由 WHATWG 在 HTML 标准内维护。<sup>[11](https://www.w3.org/standards/history/eventsource/)</sup><sup> • </sup><sup>[7](https://jakarta.ee/specifications/restful-ws/3.0/jakarta-restful-ws-spec-3.0.pdf)</sup>

## 浏览器之外的用途

由于 SSE 是纯 HTTP，非浏览器系统也将其采纳为流式格式。RFC 8895 使用 SSE 在 HTTP/1.1 上传输 ALTO（应用层流量优化）的增量更新。<sup>[3](https://www.rfc-editor.org/rfc/rfc8895.html)</sup> JSON 邮件访问协议 JMAP 让客户端通过 `text/event-stream` 资源接收推送通知，使用 `Last-Event-ID` 头来确定遗漏的变更。<sup>[12](https://www.rfc-editor.org/pdfrfc/rfc8620.txt.pdf)</sup> Azure OpenAI 的补全与聊天 API 在 `stream` 参数设为 true 时，通过 SSE 逐词元流式输出模型结果。<sup>[13](https://learn.microsoft.com/en-us/answers/questions/1409726/streaming-with-azure-openai-api)</sup> 模型上下文协议的可流式 HTTP 传输可以将连接升级为 SSE 以处理长时间运行的任务，Microsoft Foundry 的托管代理平台则期望来自代理容器的、内容类型为 `text/event-stream` 的 SSE 流。<sup>[14](https://blog.cloudflare.com/streamable-http-mcp-servers-python/)</sup><sup> • </sup><sup>[15](https://learn.microsoft.com/en-us/azure/foundry/agents/concepts/hosted-agent-contract)</sup>

## References

1. [HTML Standard, section 9.2 Server-sent events, WHATWG](https://html.spec.whatwg.org/multipage/server-sent-events.html)
2. [EventSource, MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)
3. [RFC 8895: ALTO Incremental Updates Using Server-Sent Events (SSE), IETF](https://www.rfc-editor.org/rfc/rfc8895.html)
4. [HTML Standard, section on communication, WHATWG](https://html.spec.whatwg.org/multipage/comms.html)
5. [Server-sent events, MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events)
6. [Understanding the Event Stream Format, server-sent-events.com](https://www.server-sent-events.com/sse-protocol-fundamentals-architecture/understanding-the-event-stream-format/)
7. [Jakarta RESTful Web Services 3.0, chapter 9 Server-Sent Events, Jakarta EE](https://jakarta.ee/specifications/restful-ws/3.0/jakarta-restful-ws-spec-3.0.pdf)
8. [Last-Event-ID response if unavailable, whatwg/html issue #8297](https://github.com/whatwg/html/issues/8297)
9. [EventSource close, whatwg/html issue #3380](https://github.com/whatwg/html/issues/3380)
10. [Safelist Last-Event-ID, whatwg/fetch issue #568](https://github.com/whatwg/fetch/issues/568)
11. [Server-Sent Events publication history, W3C](https://www.w3.org/standards/history/eventsource/)
12. [RFC 8620: The JSON Meta Application Protocol (JMAP), IETF](https://www.rfc-editor.org/pdfrfc/rfc8620.txt.pdf)
13. [Streaming with Azure OpenAI API, Microsoft Q&A](https://learn.microsoft.com/en-us/answers/questions/1409726/streaming-with-azure-openai-api)
14. [Bringing streamable HTTP transport and Python language support to MCP servers, Cloudflare Blog](https://blog.cloudflare.com/streamable-http-mcp-servers-python/)
15. [Hosted agent runtime contract, Microsoft Foundry](https://learn.microsoft.com/en-us/azure/foundry/agents/concepts/hosted-agent-contract)

---
*Initially written Sep 17, 2026 · Reviewed: Oct 15, 2026 · Edited: Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › 数据格式与序列化

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/server-sent-events

English original: https://www.edgepedia.org/server-sent-events
