代码
import socketio
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse
# app
app = FastAPI()
# socketio
sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins=[])
app.mount("/ws", socketio.ASGIApp(sio))
# cros
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def index():
return RedirectResponse(url="/docs", status_code=303)
@app.get('/student')
async def student():
return {'data': 'alice'}
@sio.event
async def connect(sid, environ):
print(f'sid={sid}, environ={environ}')
await sio.emit("connect", 'connect success!!!')
@sio.on('join')
async def ping_message(sid, data):
print(data)
await sio.emit("join", 'hello!~~ from server', room=sid)
关键代码
- 其次要注意版本匹配问题