【FastAPI】实现服务器向客户端发送SSE(Server-Sent Events)广播

在FastAPI中实现服务器向客户端发送SSE(Server-Sent Events)广播,可以通过以下步骤实现。SSE是一种服务器推送技术,允许服务器发送实时数据到客户端,通常用于创建实时更新的应用程序。

1. 安装必要的依赖

首先,确保你已经安装了FastAPI和Uvicorn:

bash 复制代码
pip install fastapi uvicorn

2. FastAPI服务器实现SSE广播

FastAPI使用StreamingResponse可以实现SSE。以下是一个实现SSE广播的简单例子,服务器会定期向所有连接的客户端广播消息。

python 复制代码
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
from typing import List
import asyncio

app = FastAPI()

# 用于保存所有的客户端连接
clients: List[asyncio.Queue] = []

# SSE生成器,用于向客户端发送事件流
async def event_generator():
    queue = asyncio.Queue()  # 每个客户端拥有自己的消息队列
    clients.append(queue)
    try:
        while True:
            data = await queue.get()  # 等待新消息
            yield f"data: {data}\n\n"
    except asyncio.CancelledError:
        clients.remove(queue)  # 客户端断开连接时移除其队列
        raise

# SSE endpoint,用于客户端连接
@app.get("/sse")
async def sse(request: Request):
    # 返回SSE流
    return StreamingResponse(event_generator(), media_type="text/event-stream")

# 广播消息到所有客户端
async def broadcast_message(message: str):
    for queue in clients:
        await queue.put(message)  # 将消息放入所有客户端的队列中

# 定期发送广播消息
@app.on_event("startup")
async def startup_event():
    async def send_messages():
        count = 0
        while True:
            await asyncio.sleep(5)  # 每5秒发送一次消息
            await broadcast_message(f"Server message: {count}")
            count += 1

    asyncio.create_task(send_messages())

3. 客户端实现

客户端可以使用EventSource对象来接收SSE事件流。以下是一个简单的HTML客户端代码:

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>SSE Demo</title>
</head>
<body>
    <h1>Server-Sent Events</h1>
    <div id="messages"></div>

    <script>
        const eventSource = new EventSource("/sse");

        eventSource.onmessage = function(event) {
            const newMessage = document.createElement("div");
            newMessage.textContent = event.data;
            document.getElementById("messages").appendChild(newMessage);
        };

        eventSource.onerror = function() {
            console.log("Error occurred or connection closed.");
        };
    </script>
</body>
</html>

4. 运行FastAPI服务器

使用Uvicorn运行服务器:

bash 复制代码
uvicorn main:app --reload

这样,服务器会每5秒向所有连接的客户端广播消息。客户端只需要访问/sse即可建立与服务器的SSE连接,并实时接收服务器推送的消息。

关键点说明:

  • SSE(Server-Sent Events) :服务器通过text/event-stream向客户端推送数据,客户端通过EventSource接收。
  • 广播实现:将消息放入所有客户端的队列中,确保每个连接的客户端都能接收到消息。
  • StreamingResponse:用于持续向客户端发送数据流。

这样,你就可以在FastAPI中实现一个SSE广播功能了。

相关推荐
MarkHD2 分钟前
调度、监控与部署:Python自动化任务全栈实践
开发语言·python·自动化
桌面运维家2 分钟前
服务器负载均衡异常流量监控与安全防护实战
服务器·安全·负载均衡
m0_748920362 分钟前
如何让点击目标元素时随机移动到页面任意位置
jvm·数据库·python
Resistance丶未来3 分钟前
DeepSeek-V4 新手快速上手指南
数据结构·python·gpt·算法·机器学习·claude·claude 4.6
idolao7 分钟前
CentOS 7 安装 jprofiler_linux64_7_2_3.tar.gz 详细步骤(解压、配置、远程连接)
linux·python·centos
qq_206901399 分钟前
如何创建CDB公共用户_C##前缀强制规则与CONTAINER=ALL.txt
jvm·数据库·python
深度学习lover12 分钟前
<数据集>yolo 家庭垃圾识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·家庭垃圾识别
江山与紫云13 分钟前
告别重复造轮子:Codex写脚本
开发语言·python
Go 言 Go 语13 分钟前
Claude Code 核心加载机制详解
服务器·前端·数据库
weixin_5689960614 分钟前
golang如何实现多活架构方案_golang多活架构方案实现教程
jvm·数据库·python