fastapi 集成python-socketio的简单说明

参考使用

  • 安装依赖
pip  install  fastapi uvicorn python-socketio
  • 1.
  • 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>
  • 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.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.

说明

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

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

参考资料

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