Node.js 服务器上的 React Native Socket.IO 未连接

问题描述 投票:0回答:1
我正在构建一个 React Native Expo 应用程序,需要使用 socket.io 进行实时通信。我正在本地主机上运行 Node.js 服务器。 这是我的代码

React Native - home.js

import { io } from "socket.io-client"; const socket = io.connect("http://127.0.0.1:4000");
Node.js - 索引.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}`); });
由于某种原因,当我尝试从前端连接到服务器时,没有任何反应。我该如何解决这个问题才能进行实时沟通?

node.js react-native socket.io expo real-time
1个回答
0
投票
home.js

import { io } from "socket.io-client"; const socket = io.connect("<Your IP>:4000");
对于ip你需要打开cmd(windows)或终端(mac)

Windows:ipconfig

mac:ifconfig

© www.soinside.com 2019 - 2024. All rights reserved.