gpt4 book ai didi

node.js - 即使在建立 Websocket 之后,Socket IO 仍保持(重新?)连接

转载 作者:太空宇宙 更新时间:2023-11-03 23:53:29 25 4
gpt4 key购买 nike

我正在尝试实现 websockets。它设法建立连接并打印 Backend,connected!Frontend,connected!,但是当我在输入中键入文本并按发送时,它只是打印 Frontend,connected! 多次,但没有任何反应。我在这里做错了什么?

这是我所拥有的:

// server.js
const express = require("express");

const app = express();

app.use("/api/messages", require("./routes/api/messages"));

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log(`Listening on port ${PORT}`));
// routes/api/messages.js
const express = require("express");

const router = express.Router();

const server = require("http").createServer();

const io = require("socket.io")(server, {
path: "/socket",
serveClient: false,
pingInterval: 10000,
pingTimeout: 5000,
cookie: false
});

io.on("connection", () => {
console.log("Backend, connected!");
});

io.on("msg", function(msg) {
console.log("entered!"); // <--- never prints!
console.log("message: " + msg);
});

server.listen(5001);

router.post(...)

router.get(...)

module.exports = router;

在我的 React Native 前端,在 React Navigation 的一个屏幕中:

const Conversation = ({
navigation,
auth: { user },
sendMessage
}) => {
const [replyText, setReplyText] = useState("");

const socket = io("http://192.168.112.110:5001", {
path: "/socket",
transports: ["websocket"],
jsonp: false
});

useEffect(() => {
socket.connect();

socket.on("connect", () => {
console.log("Frontend, connected!");
});

socket.on("works?", () => {
console.log("omg");
});

socket.on("connect_error", err => {
console.log("error", err);
});
}, []);

const handleSendReply = () => {
if (validateLength(replyText) === 0) {
setReplyTooShort(true);

return;
}

sendMessage(
replyText,
user.username
);

console.log("replyText", replyText); // prints

socket.emit("msg", replyText);

setReplyText("");
};

return <View>
<Input
label="reply"
value={replyText}
onChangeText={e => setReplyText(e)}
/>
<View style={{ alignItems: "flex-end" }}>
<Icon
name="md-send"
type="ionicon"
iconStyle={{ paddingLeft: 20, paddingRight: 20, paddingTop: 10 }}
onPress={() => handleSendReply()}
/>
</View>
</View>
}

"socket.io": "^2.3.0"//服务器

"socket.io-client": "^2.3.0"//客户端

<小时/>

编辑:

(根据 this comment 应忽略黄色警告)

img

最佳答案

Socket 服务器监听连接事件。
连接成功后,将创建一个具有唯一 ID 的新套接字对象。
此 Socket 对象处理事件/数据的发送和接收。


io.on("connection", (socket) => {
// console.log("Backend, connected!"); // user or client is connected.
console.log("User connected with a unique socketId ", socket.id);
socket.on("msg", function (msg) {
console.log("entered!"); // <--- It will print now !
console.log("message: " + msg);
});

});

Socket-io docs

关于node.js - 即使在建立 Websocket 之后,Socket IO 仍保持(重新?)连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58376287/

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