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

Python socketio客户端无法连接Node.js Socket.io服务端问题求助

Python-socketio客户端连接Node.js Socket.io服务端问题排查

问题背景

我尝试使用python-socketio构建Python客户端,连接基于Express框架的Node.js Socket.io服务端。目前Python客户端可正常连接Python服务端,且已核对版本:Node.js使用socket.io版本^4.7.4,Python使用python-engineio==4.8.2和python-socketio==5.11.0,根据官方版本兼容表,该版本组合理应兼容。

服务端代码

主文件

// Server Code
import * as dotenv from 'dotenv'
import express, { Request, Response } from 'express'
import { createServer } from 'node:http'
import { Server, Socket } from "socket.io";
import cors from 'cors'

//App Varaibles 
dotenv.config()

//intializing the express app 
const app = express();

//using the dependancies
app.use(cors());
app.use(express.json())

const server = createServer(app);
const io = new Server(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
});

app.get('/', (req: Request, res: Response) => {
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket: Socket) => {
    console.log('a user connected');
    socket.on('disconnect', () => {
        console.log("user disconnected");
    });
});

//exporting server
module.exports = server;

启动文件

// Running Server
require("dotenv").config();
const server = require(".");

const PORT = process.env.PORT || 3000

//Listing to the app and running it on PORT 5000
server.listen(PORT, async () => {
   console.log(`listening on port ${PORT}`)
})

Python客户端代码

# Python client
import socketio

sio = socketio.Client(logger=True, engineio_logger=True)

@sio.event
def connect():
    print('connection established')

@sio.event
def my_message(data):
    print('message received with ', data)
    sio.emit('my response', {'response': 'my response'})

@sio.event
def disconnect():
    print('disconnected from server')

sio.connect('http://localhost:5000')
sio.wait()

问题排查及解决方案

1. 端口不匹配

服务端启动代码中默认端口为3000(PORT = process.env.PORT || 3000),但Python客户端连接的是5000端口。若未配置PORT环境变量,服务端会运行在3000端口,导致客户端无法连接。

解决:将客户端连接地址改为http://localhost:3000,或在服务端配置环境变量PORT=5000。

2. CORS配置不完整

当前Socket.io服务端的CORS配置仅允许GET和POST方法,WebSocket连接需要通过OPTIONS预检请求,且可能需要放宽头信息限制。

解决:更新Socket.io的CORS配置:

const io = new Server(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST", "OPTIONS"],
        allowedHeaders: "*",
        credentials: true
    }
});

3. 传输方式兼容性

部分环境下,默认传输方式可能存在兼容问题,可强制指定兼容的传输方式。

解决:在Python客户端连接时添加transports参数:

sio.connect('http://localhost:3000', transports=['websocket', 'polling'])

4. 模块系统冲突

服务端主文件使用ES模块(import),但启动文件使用CommonJS(require),可能导致模块导出不兼容。

解决:

  • 在package.json中添加"type": "module",将项目设置为ES模块模式;
  • 修改主文件的导出方式:
    export default server;
    
  • 修改启动文件为ES模块格式:
    import "dotenv/config";
    import server from "./index.js";
    
    const PORT = process.env.PORT || 3000
    
    server.listen(PORT, async () => {
       console.log(`listening on port ${PORT}`)
    })
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 07:07:45