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

使用Socket.io连接Python服务器时反复出现404错误排查

问题分析与解决方案

错误原因总结

403 Forbidden 错误

直接原因是CORS配置未包含测试客户端的来源地址,你的origins列表仅添加了https://www.piesocket.com,而本地测试工具、Dart客户端的地址(如127.0.0.1:56005、127.0.0.1:57251)不在允许范围内,导致服务器拒绝跨域连接请求。

404 Not Found / 400 Bad Request 错误

主要由两个因素导致:

  1. CORS预检请求失败(400)后,后续的Socket.io握手请求无法正常处理,返回404;
  2. 客户端与服务器端Socket.io版本不兼容,握手协议不匹配导致服务器无法识别请求路径。

修复步骤

1. 完善CORS配置

将所有测试用的客户端来源添加到origins列表,同时保证SocketManager的跨域配置与FastAPI的CORS配置一致:

from fastapi import FastAPI
from fastapi_socketio import SocketManager
from fastapi.middleware.cors import CORSMiddleware

# 包含所有需要测试的客户端地址,生产环境替换为具体的可信域名
origins = [
    'https://www.piesocket.com',
    'http://localhost:3000',  # 假设前端客户端端口
    'http://127.0.0.1:56005', # 第三方测试工具端口
    'http://127.0.0.1:57251', # Dart客户端端口
    # 测试阶段可临时用 '*' 允许所有来源,生产环境禁止使用
    # '*'
]

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

sio = SocketManager(
    app=app,
    cors_allowed_origins=origins
)

@sio.on('join')
async def handle_join(sid, *args, **kwargs):
    print('Emitting...')
    await sio.emit('test', 'Success!')
    print('Success!')

@sio.on('connect')
async def handle_connect(sid, *args, **kwargs):
    print(f'Client {sid} connected')
    await sio.emit('test', 'Success!', room=sid)  # 指定room仅发给当前连接客户端,更合理
    print('Success!')

@sio.on('test')
async def handle_test(sid, *args, **kwargs):
    await sio.emit('hey', 'joe', room=sid)

2. 验证Socket.io版本兼容性

确保客户端与服务器端的版本匹配,对应关系如下:

  • Socket.io客户端v4.x → python-socketio v5.x
  • Socket.io客户端v3.x → python-socketio v4.x
  • Socket.io客户端v2.x → python-socketio v3.x

执行pip show python-socketio查看服务器端版本,调整客户端或服务器端版本至兼容。

3. 使用正确的ASGI启动命令

必须用uvicorn等ASGI服务器启动应用,命令示例:

uvicorn main:app --host 0.0.0.0 --port 8000 --reload

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:01:54