如何连接域名子路径下FastAPI+Gunicorn的自定义命名空间Socket.IO?
解决FastAPI子路径下Socket.IO自定义命名空间连接问题
核心问题分析
你错误地把Socket.IO的服务挂载路径和命名空间混在了一起:
/fast-api-app/socket.io是Socket.IO服务的基础访问路径(对应服务端挂载的子路径)custom-ns-1是命名空间,需要作为独立参数传递,不能拼到path里
正确的客户端连接代码
方式1:直接使用io()函数
不需要手动拼接路径和命名空间,分开指定即可:
const socket = io('https://domain.com', { path: '/fast-api-app/socket.io', // 仅指定Socket.IO服务的基础路径 transports: ['websocket'], autoConnect: false }); // 连接到自定义命名空间 const customNsSocket = socket.io('/custom-ns-1');
方式2:使用Manager类(适配多命名空间场景)
注意把服务基础路径放在Manager的配置里,命名空间单独传给socket()方法:
const manager = new Manager('https://domain.com', { path: '/fast-api-app/socket.io', // 服务的基础挂载路径 reconnectionDelayMax: 10000, transports: ['websocket'], autoConnect: false }); // 单独指定目标命名空间 const customNsSocket = manager.socket('/custom-ns-1');
服务端配置验证(必查)
确保你的FastAPI服务端正确把Socket.IO挂载到子路径下,示例代码参考:
from fastapi import FastAPI import socketio # 创建Socket.IO异步实例 sio = socketio.AsyncServer(cors_allowed_origins="*") app = FastAPI() # 将Socket.IO挂载到指定子路径 app.mount('/fast-api-app/socket.io', socketio.ASGIApp(sio)) # 注册自定义命名空间的连接事件 @sio.on('connect', namespace='/custom-ns-1') async def connect_custom_ns(sid, environ): print(f"客户端 {sid} 连接到 custom-ns-1")
常见排查点
- 检查CORS配置:确保服务端允许前端域名的跨域请求,命名空间的路径不会被CORS规则拦截
- 查看浏览器控制台的WebSocket请求:确认请求URL是
wss://domain.com/fast-api-app/socket.io/?EIO=4&transport=websocket&sid=xxx,命名空间会在后续通信帧中传递 - 绝对不要在
path参数中包含命名空间,否则服务端无法识别,会默认 fallback 到/命名空间
内容的提问来源于stack exchange,提问作者sidhant jain
相关产品推荐
相关产品推荐

