Server-Sent Events (SSE) 是一种服务端推送技术,通过 HTTP 连接让客户端自动接收服务端实时消息。Server-Sent Events EventSource API 已经是 W3C HTML5 标准.

为什么需要 SSE?

对比于原生应用采用 TCP 或 UDP 进行数据传输,移动端应用要实现流式/实时网络请求,能够采取的方案不多:

  • Polling Ajax / JSONP(轮询)

  • Websockets

  • Flash(2020年停止更新)

  • Server-Sent Events (SSE)

每一种都有其优缺点,但是轮询或创建过多的连接请求,websockets 需要 HTTP upgrade。

优点

最大的优点是轻量级,使用原生 HTTP 协议,实现非常简单,默认支持断线重连。当前主流浏览器基本都支持。

优化重连

EventSources 默认自动重连,但是可以根据实际需求进行优化:

Send a line of retry: to configure the client’s reconnection time.

Send a line of id: before a data line to associate an unique id with the event. The browser will keep track of that id and in case of a reconnection will add Last-Event-ID as an HTTP header to let the server be smart about what to send the client straight away.

应用

  • 实时日志监控

参考