SSE使用介绍
- 2025-12-09 23:54:00
- admin
- 原创 112
一、SSE使用介绍
1、Flask帮助文档:https://flask.palletsprojects.com/en/stable
2、HTTP传输编码:https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Transfer-Encoding
3、SSE规范:https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
4、SSE规范:https://html.spec.whatwg.org/multipage/server-sent-events.html
5、SSE,Server-Sent Events,Event Stream,一种基于HTTP的服务端推送技术;
6、SSE,基于chunked,多次返回数据,${chunk-length}\r\n${chunk-data}\r\n
7、${chunk-length}表示${chunk-data}的字节长度,使用十六进制表示;
8、数据传输完成,需要额外传输 0\r\n\r\n 表示结束;
09、SSE服务端示例:estreamserver.py
10、SSE客户端示例:estreamclient.py
11、SSE客户端示例:estreamclient2.py
httpx:
1、python的下一代http请求客户端;
2、帮助文档:https://www.python-httpx.org
3、代码仓库:https://github.com/encode/httpx
4、本地安装:pip install httpx
fetch-event-source:
1、一个更好的eventsource请求工具,同时支持fetch特性;
2、代码仓库:https://github.com/Azure/fetch-event-source
3、本地安装:npm install @microsoft/fetch-event-source
EventSource请求详解:
1、SSE请求:var source = new EventSource(url)
2、SSE状态:EventSource.readyState,CONNECTING、OPEN、CLOSED
3、SSE事件处理:source.onopen、source.onmessage、source.onerror
4、服务端每次发送若干消息,每个消息使用 \n\n 分隔;
5、每个消息包含若干行,每行都是:[field]: value\n
6、字段名取值包含:id、event、data、retry
7、字段名为空是注释: : This is a comment
EventSource请求示例:
var url = "http://127.0.0.1:5000/events";
var source = new EventSource(url);
source.onmessage = function(event) {
var data = event.data;
console.log("******onmessage******");
console.log(data);
}
source.onerror = function(event) {
console.log("******onerror******");
source.close()
}
二、SSE消息示例
单行消息,只触发一个onmessage:
data: some text\n\n
多行消息,只触发一个onmessage:
data: another message\n
data: with two lines\n\n
SSE请求头:
GET /events HTTP/1.1
Host: 127.0.0.1:5000
User-Agent: python-requests/2.32.3
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
SSE返回头:
HTTP/1.1 200 OK
Server: Werkzeug/3.1.4 Python/3.12.3
Date: Tue, 09 Dec 2025 16:30:46 GMT
Content-Type: text/event-stream; charset=utf-8
Transfer-Encoding: chunked
Connection: close
SSE请求头:EventSource
GET /events HTTP/1.1
Host: 127.0.0.1:5000
Connection: keep-alive
Cache-Control: no-cache
User-Agent: Mozilla/5.0
Accept: text/event-stream
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: http://127.0.0.1:5000/events
Accept-Encoding: gzip, deflate, br, zstd
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8