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}`);
});
由于某种原因,当我尝试从前端连接到服务器时,没有任何反应。我该如何解决这个问题才能进行实时沟通?
import { io } from "socket.io-client";
const socket = io.connect("<Your IP>:4000");
对于ip你需要打开cmd(windows)或终端(mac)Windows:ipconfig
mac:ifconfig