fastapi socketio 简单使用

fastapi 集成python-socketio的简单说明

参考使用

  • 安装依赖
pip  install  fastapi uvicorn python-socketio
  • backend 代码
from fastapi import FastAPI,Body
 
from fastapi.middleware.cors import CORSMiddleware
import  socketio
# 注意namespaces * 可以接受各种namespace,默认是/ 
sio = socketio.AsyncServer(cors_allowed_origins='*',namespaces="*",async_mode='asgi')
 
@sio.on("connect",namespace="*")
async def connect(namespace, sid,env,auth):
    print(f"Client {namespace},{sid} connected to namespace {auth}")
    if auth["token"] != "demoapp":
        return False
 
 
@sio.event(namespace="*")
def disconnect(namespace,sid):
    print('disconnect ', sid,namespace)
 
@sio.on('*',namespace="*")
async def any_event(event,namespace,sid, data):
    print(type(event),type(sid),type(namespace),type(data))
    print(event,sid,namespace, data)
    await sio.emit("dalong", data, namespace="/appdemo")
 
app = FastAPI()
 
app.add_middleware(CORSMiddleware,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"])
 
@app.get("/")
async def demo():
    return {"message": "Hello World"}
 
 
@app.post("/send_message/{sid}")
async def send_message(sid:str,message: str = Body()):
    await sio.emit('message', message, to=sid)
    return {"message": f"Message sent to client {sid}: {message}"}
# socketio ASGIApp 包装
app.mount("/message", socketio.ASGIApp(sio, socketio_path="/message"))
 
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0",port=8000)
  • web 集成
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>socketio</title>
</head>
<body>
 
    <script src="https://cdn.socket.io/4.0.1/socket.io.js"></script>
    <script>
      // demoapp 是namespace ,path 是自定义的path ,auth 是自定义的认证机制
       var socket = io('http://localhost:8000/demoapp',{
            path: "/message",
            auth: {
                token: "demoapp"
            }
        })
        socket.on('connect', function(){
            console.log('connected');
        });
        socket.on('message', function(data){
            console.log(data);
        });
        socket.on("dalong", function(data){
            console.log(data);
        });
        socket.on('disconnect', function(){
            console.log('disconnected');
        });
    </script>
</body>
</html>

说明

以上是一个简单说明,python-socketio 的使用还是比较简单的,对于支持ha 以及集群模式的,可以配置redis 以及其他队列服务
参考配置

mgr = socketio.AsyncRedisManager('redis://')
sio = socketio.AsyncServer(client_manager=mgr)

参考资料

https://python-socketio.readthedocs.io/en/stable/index.html
https://github.com/miguelgrinberg/python-socketio

posted on   荣锋亮  阅读(101)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2023-08-08 dbt 新的基于视图的物化能力
2023-08-08 dbt modules 宏简单说明
2022-08-08 jprofiler Alpine 容器集成
2022-08-08 .net 调用spring boot rest api 的100-Continue问题
2019-08-08 apache pinot-docker-compose 运行试用
2019-08-08 Thanos prometheus 集群以及多租户解决方案docker-compose 试用(一)
2018-08-08 opencrud 中文参考翻译(完成部分)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示