React Native Expo应用Socket.IO无法连接本地Node.js服务器求助
解决React Native Expo与Node.js Socket.IO实时通信连接问题
问题背景
开发React Native Expo应用时,尝试通过Socket.IO与本地Node.js服务器建立实时通信,但前端连接无响应。更新代码添加错误监听后,控制台报错:this is the error - [Error: websocket error](翻译:连接错误 - [错误:WebSocket 错误])
原React Native代码(home.js)
import { io } from "socket.io-client"; const socket = io.connect("http://127.0.0.1:4000");
原Node.js服务器代码(index.js)
const express = require("express"); const app = express(); const PORT = 4000; app.use(express.urlencoded({ extended: true })); app.use(express.json()); const http = require("http").Server(app); const cors = require("cors"); app.use(cors()); const socketIO = require('socket.io')(http, { cors: { origin: "<http://localhost:3000>" } }); //👇🏻 Add this before the app.get() block socketIO.on('connection', (socket) => { console.log(`⚡: ${socket.id} user just connected!`); socket.on('disconnect', () => { socket.disconnect() console.log('🔥: A user disconnected'); }); }); app.get("/api", (req, res) => { res.json({ message: "Hello world", }); }); app.listen(PORT, () => { console.log(`Server listening on ${PORT}`); });
更新后的前端代码及报错
const socket = io.connect("http://127.0.0.1:4000", { transports: ['websocket'] }); socket.on("connect_error", (e) => { console.log("this is the error - ", e) });
控制台报错:this is the error - [Error: websocket error]
解决方案
1. 修正服务器启动方式
Socket.IO绑定的是http服务器实例,而非Express的app,需替换启动代码:
// 替换原app.listen(...)为以下代码 http.listen(PORT, () => { console.log(`Server listening on ${PORT}`); });
2. 修复CORS配置
- 服务器端Socket.IO的CORS origin配置多了多余尖括号,修正为:
const socketIO = require('socket.io')(http, { cors: { origin: "http://localhost:3000", methods: ["GET", "POST"] // 可选,明确允许的请求方法 } });
- 针对Expo测试场景调整服务器地址:
- Android模拟器:用
http://10.0.2.2:4000替代127.0.0.1 - iOS模拟器:直接使用
http://localhost:4000 - 真机测试:确保手机与电脑在同一局域网,用电脑的局域网IP(如
http://192.168.x.x:4000)
- Android模拟器:用
3. 优化前端Socket连接配置
添加更多监听事件排查问题,同时保留轮询作为WebSocket的降级方案:
import { io } from "socket.io-client"; import { Platform } from 'react-native'; // 根据运行环境自动选择服务器地址 const serverUrl = Platform.OS === 'android' ? 'http://10.0.2.2:4000' : 'http://localhost:4000'; const socket = io(serverUrl, { transports: ['websocket', 'polling'], reconnection: true, reconnectionDelay: 1000, reconnectionDelayMax: 5000 }); // 监听关键连接事件 socket.on("connect", () => { console.log("Socket连接成功,ID:", socket.id); }); socket.on("connect_error", (error) => { console.error("连接错误详情:", error.message); }); socket.on("disconnect", () => { console.log("Socket已断开连接"); });
4. 确保客户端与服务器版本兼容
Socket.IO客户端和服务器版本需保持一致,建议使用4.x系列:
- 服务器端安装:
npm install socket.io@4.x - 客户端安装:
npm install socket.io-client@4.x
内容的提问来源于stack exchange,提问作者Itay Lador
相关产品推荐
相关产品推荐

