Socket.io连接异常:Engine.io请求返回404/超时求助
Socket.io 连接返回404/超时问题排查与解决
问题现象
- 客户端控制台反复输出
https://example.com/socket.io/?EIO=4&transport=polling&t=OUAHy-a 404,偶现请求超时 - 代码基于Socket.io官方文档修改,未使用localhost
- 已尝试添加
cors: origin="*"无效,托管服务不支持部分视频中的修复方案
客户端代码
HTML
<!DOCTYPE html> <html> <head> <title>Zesty testy</title> </head> <body> <script src="https://cdn.socket.io/4.4.1/socket.io.js"></script> <script src="./client.js"></script> </body> </html>
JS
const socket = io();
服务器代码
var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); io.on('connection', (socket) => { console.log('a user connected'); }); server.listen(3000, () => { console.log('listening on *:3000'); });
排查与解决步骤
确认客户端连接地址
io()默认连接当前页面域名的根路径,若Socket.io服务部署在不同端口/子路径,需显式指定地址:const socket = io("https://example.com:3000");注意:确认托管服务的端口映射规则,对外暴露的端口是否为3000。
修正服务器CORS配置
Socket.io v4需要完整的CORS配置对象,仅设置origin="*"可能无效,修改服务器代码:var io = require('socket.io')(server, { cors: { origin: "https://example.com", // 替换为你的客户端域名 methods: ["GET", "POST"], credentials: true } });测试阶段可临时用
origin: "*",生产环境需指定具体域名。验证服务器端口监听与权限
- 确认服务器正常监听3000端口,执行
netstat -tulpn | grep 3000(Linux)或查看进程端口占用情况 - 检查托管服务的防火墙/安全组规则,是否开放3000端口的入站请求
- 确认服务器正常监听3000端口,执行
检查反向代理配置(若存在)
若托管服务使用反向代理(如Nginx),需配置转发Socket.io请求:location /socket.io/ { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; }若托管服务不允许自定义代理配置,联系服务商确认是否支持WebSocket转发。
确保版本兼容
客户端使用4.4.1版本,服务器需安装同版本或兼容版本:npm uninstall socket.io npm install socket.io@4.4.1直接测试服务端点
在浏览器访问https://example.com:3000/socket.io/,若返回{"code":0,"message":"Transport unknown"}说明服务端正常;若返回404,说明服务未正确启动或路径映射错误。
内容的提问来源于stack exchange,提问作者Vairoon
相关产品推荐
相关产品推荐

