一、SSE介绍
服务端推送
在服务器推送技术中,服务器在消息可用后立即主动向客户端发送消息。其中,有两种类型的服务器推送:SSE和 WebSocket。
SSE(Server-Send Events)
SSE 是一种在基于浏览器的 Web 应用程序中仅从服务器向客户端发送文本消息的技术。SSE基于 HTTP 协议中的持久连接, 具有由 W3C 标准化的网络协议和 EventSource 客户端接口,作为 HTML5 标准套件的一部分。
二、使用SSE实现流式输出
1、安装依赖库
pip install asyncio
pip install sse-starlette
2、后端代码
import json
from fastapi import FastAPI, Query, Path
import uvicorn
from starlette.requests import Request
import asyncio
from sse_starlette import EventSourceResponse
app = FastAPI()
@app.get("/stream")
async def flush_stream(request: Request):
async def event_generator(request: Request):
res_str = "这是一个流式输出他会将每个字挨个挨个的输出哈哈!!!"
for idx, word in enumerate(res_str):
if await request.is_disconnected():
print("连接已中断")
break
data = json.dumps({"id": idx, "message": word}, ensure_ascii=False)
yield data
await asyncio.sleep(1)
return EventSourceResponse(event_generator(request))
if __name__ == '__main__':
uvicorn.run("Run:app", host="0.0.0.0", port=8080)
三、测试
四、客户端监听 SSE 事件
客户端需要监听服务器发送的事件。在浏览器中,可以使用 JavaScript 的 EventSource
对象来监听 SSE。
const eventSource = new EventSource('/stream');
eventSource.onmessage = function(event) {
console.log(event.data);
};
eventSource.onerror = function(error) {
console.error('EventSource failed:', error);
};