gpt4 book ai didi

node.js - 套接字IO 3.0,不接收服务器上的发射

转载 作者:行者123 更新时间:2023-12-03 12:07:11 25 4
gpt4 key购买 nike

后配置

import express from "express";
import SocketIO from "socket.io";
import http from "http";
import cors from "cors";

const app = express();
app.use(cors());
const server = http.createServer(app);
const io = SocketIO(server);

const PORT = 5000;

io.on("connection", (socket) => {
console.log("Connected!!");

socket.on("send_message", (data) => {
console.log('SEND_MESSAGE');
console.log(data);
});

socket.on("disconnect", () => {
console.log("Close.-.--.");
});
});

server.listen(PORT, () => {
console.log(`Server on port => ${PORT}`);
});

前线实现
import io from "socket.io-client";

let socket;

const Home = () => {
useEffect(() => {
socket = io("localhost:5000", {
// transports: ["websocket"],
// upgrade: false,
});

return () => socket.disconnect();
}, []);


const onEnter = () => {
socket.emit("send_message", { message: messageToSend });
setMessageToSend("");
};


我收到了Connect and Disconnect发出的消息,但是我无法获得send_message发出的消息,帮助! :c,我看到一些视频和类(class)无法获得我想要的结果,不要判断我,我是套接字io的新手

最佳答案

我对React不太了解,但是在前端,应该是:

socket = io.connect("http://localhost:9000");
另外,如果它不起作用,则从 useEffect()中删除断开连接代码并进行测试。如果工作正常,则表示在发出事件触发之前,您的套接字已断开连接。

关于node.js - 套接字IO 3.0,不接收服务器上的发射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65877885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com