Socket.io与Next.js连接报错net::ERR_NAME_NOT_RESOLVED求助
Socket.io客户端连接Uvicorn服务端失败的解决方案
服务端配置修正
- 必须配置跨域并正确挂载Socket.io路由(以FastAPI为例):
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from socketio import AsyncServer app = FastAPI() # 初始化AsyncServer时允许跨域,指定ASGI模式 sio = AsyncServer(cors_allowed_origins="*", async_mode="asgi") socket_app = sio.asgi_app # 全局CORS中间件,避免请求被拦截 app.add_middleware( CORSMiddleware, allow_origins=["*"], # 生产环境替换为你的Next.js域名 allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # 将Socket.io挂载到/socket.io路径 app.mount("/socket.io", socket_app) - 启动Uvicorn时绑定正确的主机和端口:
uvicorn main:app --host 0.0.0.0 --port 8000
客户端连接参数调整
Next.js+TS端确保连接地址、路径与服务端匹配:
import { io, Socket } from "socket.io-client"; // 连接地址对应Uvicorn的地址,path必须和服务端挂载的一致 const socket: Socket = io("http://localhost:8000", { path: "/socket.io", // 显式指定传输方式,避免默认优先级导致的轮询失败 transports: ["websocket", "polling"], }); // 监听错误便于排查 socket.on("connect_error", (err) => { console.error("连接异常:", err.message); });
环境排查
- 端口占用:打开CMD执行
netstat -ano | findstr :8000,若有其他进程占用,关闭进程或更换服务端端口 - 防火墙:临时关闭Windows Defender防火墙测试,若能连接则添加Uvicorn的防火墙允许规则
版本兼容性
- 服务端
python-socketio和客户端socket.io-client版本需对齐,比如均使用4.x系列版本(版本不匹配会导致协议不兼容)
内容的提问来源于stack exchange,提问作者mikoloism
相关产品推荐
相关产品推荐

