SSE技术总结
<h1 id="参考">参考</h1><p>https://www.ruanyifeng.com/blog/2017/05/server-sent_events.html</p>
<h1 id="sse本质">SSE本质</h1>
<p>严格地说,HTTP 协议无法做到服务器主动推送信息。但是,有一种变通方法,就是服务器向客户端声明,接下来要发送的是流信息(streaming)。</p>
<p>也就是说,发送的不是一次性的数据包,而是一个数据流,会连续不断地发送过来。这时,客户端不会关闭连接,会一直等着服务器发过来的新的数据流,视频播放就是这样的例子。本质上,这种通信就是以流信息的方式,完成一次用时很长的下载。</p>
<p>SSE 就是利用这种机制,使用流信息向浏览器推送信息。它基于 HTTP 协议,目前除了 IE/Edge,其他浏览器都支持。</p>
<h1 id="sse特点">SSE特点</h1>
<p>SSE 与 WebSocket 作用相似,都是建立浏览器与服务器之间的通信渠道,然后服务器向浏览器推送信息。</p>
<p>总体来说,WebSocket 更强大和灵活。因为它是全双工通道,可以双向通信;SSE 是单向通道,只能服务器向浏览器发送,因为流信息本质上就是下载。如果浏览器向服务器发送信息,就变成了另一次 HTTP 请求。</p>
<p><img src="https://www.ruanyifeng.com/blogimg/asset/2017/bg2017052702.jpg" alt="" loading="lazy"></p>
<ul>
<li>SSE 使用 HTTP 协议,现有的服务器软件都支持。WebSocket 是一个独立协议。</li>
<li>SSE 属于轻量级,使用简单;WebSocket 协议相对复杂。</li>
<li>SSE 默认支持断线重连,WebSocket 需要自己实现。</li>
<li>SSE 一般只用来传送文本,二进制数据需要编码后传送,WebSocket 默认支持传送二进制数据。</li>
<li>SSE 支持自定义发送的消息类型。</li>
</ul>
<h1 id="客户端-api">客户端 API</h1>
<h2 id="1-eventsource-对象">1 EventSource 对象</h2>
<p>SSE 的客户端 API 部署在EventSource对象上。下面的代码可以检测浏览器是否支持 SSE。</p>
<pre><code> if ('EventSource' in window) {
// ...
}
</code></pre>
<p>上面的url可以与当前网址同域,也可以跨域。跨域时,可以指定第二个参数,打开withCredentials属性,表示是否一起发送 Cookie。</p>
<pre><code>var source = new EventSource(url, { withCredentials: true });
</code></pre>
<p>EventSource实例的readyState属性,表明连接的当前状态。该属性只读,可以取以下值。</p>
<ul>
<li>0:相当于常量EventSource.CONNECTING,表示连接还未建立,或者断线正在重连。</li>
<li>1:相当于常量EventSource.OPEN,表示连接已经建立,可以接受数据。</li>
<li>2:相当于常量EventSource.CLOSED,表示连接已断,且不会重连。</li>
</ul>
<h2 id="2-基本用法">2 基本用法</h2>
<p>连接一旦建立,就会触发open事件,可以在onopen属性定义回调函数。</p>
<pre><code>source.onopen = function (event) {
// ...
};
// 另一种写法
source.addEventListener('open', function (event) {
// ...
}, false);
</code></pre>
<p>客户端收到服务器发来的数据,就会触发message事件,可以在onmessage属性的回调函数。</p>
<pre><code>
source.onmessage = function (event) {
var data = event.data;
// handle message
};
// 另一种写法
source.addEventListener('message', function (event) {
var data = event.data;
// handle message
}, false);
</code></pre>
<p>上面代码中,事件对象的data属性就是服务器端传回的数据(文本格式)。</p>
<p>如果发生通信错误(比如连接中断),就会触发error事件,可以在onerror属性定义回调函数。</p>
<pre><code>
source.onerror = function (event) {
// handle error event
};
// 另一种写法
source.addEventListener('error', function (event) {
// handle error event
}, false);
</code></pre>
<p>close方法用于关闭 SSE 连接。</p>
<pre><code>source.close();
</code></pre>
<h2 id="3-自定义事件">3 自定义事件</h2>
<p>默认情况下,服务器发来的数据,总是触发浏览器EventSource实例的message事件。开发者还可以自定义 SSE 事件,这种情况下,发送回来的数据不会触发message事件。</p>
<pre><code>source.addEventListener('foo', function (event) {
var data = event.data;
// handle message
}, false);
</code></pre>
<p>上面代码中,浏览器对 SSE 的foo事件进行监听。如何实现服务器发送foo事件,请看下文。</p>
<h1 id="服务器实现">服务器实现</h1>
<h2 id="1-数据格式">1 数据格式</h2>
<p>服务器向浏览器发送的 SSE 数据,必须是 UTF-8 编码的文本,具有如下的 HTTP 头信息。</p>
<pre><code>Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive
</code></pre>
<p>上面三行之中,第一行的Content-Type必须指定 MIME 类型为<code>event-steam</code>。</p>
<p>每一次发送的信息,由若干个message组成,每个message之间用<code>\n\n</code>分隔。每个message内部由若干行组成,每一行都是如下格式,每行是<code>\n</code>结束。</p>
<pre><code>: value\n
</code></pre>
<p>上面的field可以取四个值。</p>
<ul>
<li>data</li>
<li>event</li>
<li>id</li>
<li>retry</li>
</ul>
<p>此外,还可以有冒号开头的行,表示注释。通常,服务器每隔一段时间就会向浏览器发送一个注释,保持连接不中断。</p>
<pre><code>: This is a comment
</code></pre>
<p>下面是一个例子。</p>
<pre><code>
: this is a test stream\n\n
data: some text\n\n
data: another message\n
data: with two lines \n\n
</code></pre>
<h2 id="2-data-字段">2 data 字段</h2>
<p>数据内容用data字段表示。</p>
<pre><code>data:message\n\n
</code></pre>
<p>如果数据很长,可以分成多行,最后一行用<code>\n\n</code>结尾,前面行都用<code>\n</code>结尾。</p>
<pre><code>data: begin message\n
data: continue message\n\n
</code></pre>
<p>下面是一个发送 JSON 数据的例子。</p>
<pre><code>data: {\n
data: "foo": "bar",\n
data: "baz", 555\n
data: }\n\n
</code></pre>
<h2 id="3-id-字段">3 id 字段</h2>
<p>数据标识符用id字段表示,相当于每一条数据的编号。</p>
<pre><code>
id: msg1\n
data: message\n\n
</code></pre>
<p>浏览器用lastEventId属性读取这个值。一旦连接断线,浏览器会发送一个 HTTP 头,里面包含一个特殊的Last-Event-ID头信息,将这个值发送回来,用来帮助服务器端重建连接。因此,这个头信息可以被视为一种同步机制。</p>
<h2 id="4-event-字段">4 event 字段</h2>
<p>event字段表示自定义的事件类型,默认是message事件。浏览器可以用addEventListener()监听该事件,下面代码使用了自定义事件<code>foo</code></p>
<pre><code>event: foo\n
data: a foo event\n\n
data: an unnamed event\n\n
event: bar\n
data: a bar event\n\n
</code></pre>
<p>上面的代码创造了三条信息。第一条的名字是foo,触发浏览器的foo事件;第二条未取名,表示默认类型,触发浏览器的message事件;第三条是bar,触发浏览器的bar事件。</p>
<h2 id="5-retry-字段">5 retry 字段</h2>
<p>服务器可以用retry字段,指定浏览器重新发起连接的时间间隔。</p>
<pre><code>retry: 10000\n
</code></pre>
<p>两种情况会导致浏览器重新发起连接:一种是时间间隔到期,二是由于网络错误等原因,导致连接出错。</p>
<h1 id="服务器实例">服务器实例</h1>
<p>SSE 要求服务器与浏览器保持连接。对于不同的服务器软件来说,所消耗的资源是不一样的。Apache 服务器,每个连接就是一个线程,如果要维持大量连接,势必要消耗大量资源。Node 则是所有连接都使用同一个线程,因此消耗的资源会小得多,但是这要求<code>每个连接不能包含很耗时</code>的操作,比如磁盘的 IO 读写。</p>
<p>下面是 springboot的SseEmitter服务器实例,它使用自定义的event,添加了id字段</p>
<pre><code>@GetMapping(value = "/sse1", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter handleSse() {
SseEmitter emitter = new SseEmitter(60_000L); // 超时时间设为 60 秒
// 异步发送数据(模拟实时推送)
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
// 推送事件(格式为 "data: 内容\n\n")
SseEmitter.SseEventBuilder builder = SseEmitter.event()
.data("SSEMessage " + i + " - " + System.currentTimeMillis())
.id(String.valueOf(i))
.name("SSEEvent");
emitter.send(builder);
// 休眠 1 秒
Thread.sleep(1000);
}
// 标记完成
emitter.complete();
} catch (Exception e) {
// 发生错误时终止连接
emitter.completeWithError(e);
}
}).start();
return emitter;
}
</code></pre>
<p>然后在谷歌浏览器访问http://localhost:8080/sse1,看一下结果如下</p>
<p><img src="https://images.cnblogs.com/cnblogs_com/lori/2457803/o_250515015428_sse3.png" alt="" loading="lazy"></p>
<h1 id="各大编程语言下的sse">各大编程语言下的SSE</h1>
<h1 id="pythongojavac-在-sse-性能方面的比较">Python、Go、Java、C# 在 SSE 性能方面的比较</h1>
<p>在选择用于 Server-Sent Events (SSE) 的开发语言时,性能是一个重要考量因素。以下是这四种语言在 SSE 场景下的性能分析和比较:</p>
<h2 id="性能综合对比">性能综合对比</h2>
<table>
<thead>
<tr>
<th>语言</th>
<th>并发性能</th>
<th>内存效率</th>
<th>连接开销</th>
<th>生态系统</th>
<th>适用场景</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Go</strong></td>
<td>⭐⭐⭐⭐⭐</td>
<td>⭐⭐⭐⭐⭐</td>
<td>⭐⭐⭐⭐⭐</td>
<td>⭐⭐⭐⭐</td>
<td>高并发、大规模连接</td>
</tr>
<tr>
<td><strong>Java</strong></td>
<td>⭐⭐⭐⭐</td>
<td>⭐⭐⭐⭐</td>
<td>⭐⭐⭐</td>
<td>⭐⭐⭐⭐⭐</td>
<td>企业级应用、复杂业务逻辑</td>
</tr>
<tr>
<td><strong>C#</strong></td>
<td>⭐⭐⭐⭐</td>
<td>⭐⭐⭐⭐</td>
<td>⭐⭐⭐</td>
<td>⭐⭐⭐⭐</td>
<td>Windows 环境、.NET 生态系统</td>
</tr>
<tr>
<td><strong>Python</strong></td>
<td>⭐⭐</td>
<td>⭐⭐</td>
<td>⭐⭐</td>
<td>⭐⭐⭐⭐</td>
<td>快速原型、中小规模应用</td>
</tr>
</tbody>
</table>
<h2 id="详细分析">详细分析</h2>
<h3 id="1-go-golang">1. Go (Golang)</h3>
<p><strong>优势:</strong></p>
<ul>
<li><strong>极高的并发性能</strong>:Go 的 goroutine 是轻量级线程,可以轻松处理数十万并发连接</li>
<li><strong>低内存开销</strong>:每个 goroutine 的初始栈大小只有 2KB,远小于传统线程</li>
<li><strong>原生并发支持</strong>:语言级别支持并发,编写高并发程序更加简单</li>
<li><strong>高效的标准库</strong>:<code>net/http</code> 包对长连接有良好支持</li>
</ul>
<p><strong>示例代码:</strong></p>
<pre><code class="language-go">package main
import (
"fmt"
"net/http"
"time"
)
func sseHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}
// 模拟持续发送事件
for {
fmt.Fprintf(w, "data: %s\n\n", time.Now().Format("2006-01-02 15:04:05"))
flusher.Flush()
time.Sleep(1 * time.Second)
}
}
func main() {
http.HandleFunc("/events", sseHandler)
fmt.Println("SSE server running on :8080")
http.ListenAndServe(":8080", nil)
}
</code></pre>
<h3 id="2-java">2. Java</h3>
<p><strong>优势:</strong></p>
<ul>
<li><strong>成熟的 NIO 框架</strong>:Netty 和 Java NIO 可以高效处理大量并发连接</li>
<li><strong>强大的线程池管理</strong>:Java 的并发工具包提供了丰富的线程管理选项</li>
<li><strong>企业级稳定性</strong>:JVM 经过多年优化,在大规模应用中表现稳定</li>
<li><strong>丰富的生态系统</strong>:Spring Framework 等提供了完善的 SSE 支持</li>
</ul>
<p><strong>示例代码(使用 Spring Boot):</strong></p>
<pre><code class="language-java">import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@RestController
public class SseController {
@GetMapping(path = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter handleSse() {
SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(() -> {
try {
emitter.send(SseEmitter.event()
.data("Current time: " + java.time.LocalDateTime.now()));
} catch (IOException e) {
emitter.completeWithError(e);
scheduler.shutdown();
}
}, 0, 1, TimeUnit.SECONDS);
emitter.onCompletion(scheduler::shutdown);
return emitter;
}
}
</code></pre>
<h3 id="3-c-net">3. C# (.NET)</h3>
<p><strong>优势:</strong></p>
<ul>
<li><strong>高效的异步编程模型</strong>:async/await 语法使高并发编程更加简单</li>
<li><strong>性能优化的运行时</strong>:.NET Core/.NET 5+ 在性能方面有显著提升</li>
<li><strong>IIS 和 Kestrel 服务器</strong>:提供高效的连接处理能力</li>
<li><strong>Windows 集成优势</strong>:在 Windows 环境中表现尤为出色</li>
</ul>
<p><strong>示例代码(使用 ASP.NET Core):</strong></p>
<pre><code class="language-csharp">using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
public class SseController : Controller
{
public async Task GetEvents()
{
Response.Headers.Add("Content-Type", "text/event-stream");
Response.Headers.Add("Cache-Control", "no-cache");
Response.Headers.Add("Connection", "keep-alive");
while (true)
{
await Response.WriteAsync($"data: {DateTime.Now}\n\n");
await Response.Body.FlushAsync();
await Task.Delay(1000);
}
}
}
</code></pre>
<h3 id="4-python">4. Python</h3>
<p><strong>优势:</strong></p>
<ul>
<li><strong>开发效率高</strong>:代码简洁,易于快速实现原型</li>
<li><strong>丰富的异步框架</strong>:如 aiohttp、FastAPI 等支持异步 SSE</li>
<li><strong>强大的生态系统</strong>:有大量可用的库和框架</li>
</ul>
<p><strong>劣势:</strong></p>
<ul>
<li><strong>全局解释器锁 (GIL)</strong>:限制了真正的并行执行,影响高并发性能</li>
<li><strong>相对较高的内存开销</strong>:与其他编译型语言相比,每个连接的内存开销较大</li>
</ul>
<p><strong>示例代码(使用 aiohttp):</strong></p>
<pre><code class="language-python">from aiohttp import web
import asyncio
import datetime
async def events(request):
response = web.StreamResponse()
response.headers['Content-Type'] = 'text/event-stream'
response.headers['Cache-Control'] = 'no-cache'
response.headers['Connection'] = 'keep-alive'
await response.prepare(request)
while True:
data = f"data: {datetime.datetime.now()}\n\n"
await response.write(data.encode('utf-8'))
await asyncio.sleep(1)
app = web.Application()
app.router.add_get('/events', events)
if __name__ == '__main__':
web.run_app(app, port=8080)
</code></pre>
<h2 id="性能基准测试参考">性能基准测试参考</h2>
<p>根据各种性能基准测试(如 TechEmpower Web Framework Benchmarks):</p>
<ol>
<li><strong>Go</strong> 通常在处理高并发连接时表现最佳,特别是在使用 fasthttp 等优化库时</li>
<li><strong>Java</strong> 在使用 Netty 或 Vert.x 等异步框架时,性能接近 Go,但内存使用较高</li>
<li><strong>C#</strong> 在 .NET Core 上表现优异,性能与 Java 相当,有时甚至更好</li>
<li><strong>Python</strong> 在纯性能方面通常落后,但在使用 uvloop 等优化时可以有不错的表现</li>
</ol>
<h2 id="选择建议">选择建议</h2>
<ol>
<li><strong>超大规模并发场景</strong>(10万+连接):选择 <strong>Go</strong>,因其极低的每连接开销和卓越的并发能力</li>
<li><strong>企业级复杂应用</strong>:选择 <strong>Java</strong> 或 <strong>C#</strong>,因其成熟的生态系统和强大的工具支持</li>
<li><strong>快速原型和中小规模应用</strong>:选择 <strong>Python</strong>,因其开发效率高</li>
<li><strong>Windows 环境或 .NET 生态系统</strong>:选择 <strong>C#</strong>,因其与 Windows 平台的深度集成</li>
<li><strong>微服务架构</strong>:<strong>Go</strong> 和 <strong>Java</strong> 都是不错的选择,取决于团队熟悉度</li>
</ol>
<h2 id="结论">结论</h2>
<p>对于 SSE 应用,从纯性能角度考虑,<strong>Go 是最佳选择</strong>,特别是在需要处理大量并发连接的场景。<strong>Java 和 C#</strong> 在性能上也非常接近,并且提供了更丰富的企业级功能。<strong>Python</strong> 虽然性能相对较低,但其开发效率和丰富的库生态系统使其在中小规模应用中仍然是一个可行的选择。</p>
<p>最终的选择应该基于您的具体需求、团队技术栈熟悉度、现有基础设施以及性能要求来综合考虑。</p>
<h1 id="参考链接">参考链接</h1>
<ul>
<li>http://jspro.com/apis/implementing-push-technology-using-server-sent-events/</li>
<li>http://cjihrig.com/blog/the-server-side-of-server-sent-events/</li>
<li>http://www.html5rocks.com/en/tutorials/eventsource/basics/</li>
<li>https://segment.io/blog/2014-04-03-server-sent-events-the-simplest-realtime-browser-spec/</li>
</ul>
</div>
<div id="MySignature" role="contentinfo">
<p></p>
<div class="navgood">
<p>作者:仓储大叔,张占岭,<br>
荣誉:微软MVP<br>QQ:853066980</p>
<p><strong>支付宝扫一扫,为大叔打赏!</strong>
<br><img src="https://images.cnblogs.com/cnblogs_com/lori/237884/o_IMG_7144.JPG"></p>
</div><br><br>
来源:https://www.cnblogs.com/lori/p/19081787
頁:
[1]