You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python-FastAPI-SocketIO 连接报403 Forbidden错误排查及示例请求

问题分析与解决方案

触发403 Forbidden的核心原因

  • 语法错误:@sio event 应为 @sio.event(缺少点号,装饰器无法正确绑定事件)
  • 框架适配错误:FastAPI是ASGI类型框架,但你使用了适配WSGI应用的socketio.WSGIApp,两者运行模式不兼容
  • 连接权限缺失:connect函数未接收会话ID参数,且未明确返回True允许连接,SocketIO默认会拒绝此类连接请求

修正后的完整示例代码

1. FastAPI主应用文件(app.py)

from fastapi import FastAPI

# 初始化FastAPI ASGI实例
server = FastAPI()

# 可选:添加普通API接口用于测试
@server.get("/")
async def root():
    return {"message": "FastAPI 运行正常"}

2. SocketIO集成文件(main.py)

import socketio
from app import server

# 创建ASGI兼容的异步SocketIO服务器,配置跨域权限
sio = socketio.AsyncServer(
    cors_allowed_origins="*",  # 生产环境建议替换为具体允许的域名
    async_mode="asgi"
)

# 将SocketIO挂载到FastAPI应用
app = socketio.ASGIApp(sio, other_app=server)

@sio.event
async def connect(sid, environ):
    print(f"客户端 {sid} 已建立连接")
    # 必须返回True明确允许连接,否则会触发403
    return True

@sio.event
async def disconnect(sid):
    print(f"客户端 {sid} 已断开连接")

3. 启动应用

使用Uvicorn(ASGI服务器)启动:

uvicorn main:app --reload

连接验证

使用SocketIO客户端连接地址:ws://localhost:8000/socket.io/?EIO=4&transport=websocket,即可正常建立连接。

内容的提问来源于stack exchange,提问作者Akhil Chakicherla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 20:17:34