[英]Socket.io not emitting messages to a specific user
I have a chat app with node.js, socket io, and React.js.我有一个聊天应用程序,其中包含 node.js、套接字 io 和 React.js。 The issue: the private message featureis not working.问题:私人消息功能不起作用。
Client-side:客户端:
socket.emit("chat message private", { userIDtoReceiveTheMessage, msg });
Then my server will listen and emit to that specific user:然后我的服务器将监听并发送给该特定用户:
socket.on("chat message private", ({ toUser, msg }) => {
console.log(`from ${id} to ${toUser}: ${msg}`);
let socketId = toUser;
io.to(socketId).emit("private msg", msg);
});
The result on the console for the server is: "from X to Y: message" (this is workings!)服务器控制台上的结果是:“从 X 到 Y:消息” (这是有效的!)
My client should receive "msg", but nothing happens:我的客户应该收到“味精”,但没有任何反应:
useEffect(() => {
socket.on("chat message", ({ nickname, msg }) => {
setChat([...chat, { nickname, msg }]);
});
socket.on("private msg", (msg) => {
console.log(msg);
setChat([...chat, msg]);
});
return () => {
socket.off();
};
}, [chat, toUser]);
Nothing shows up on the console for the specific user (or for any user).对于特定用户(或任何用户),控制台上没有显示任何内容。
PS: All other chat messages are being received in real-time. PS:所有其他聊天消息都是实时接收的。 The only issue is with the ones using:唯一的问题是那些使用:
io.to(socketId).emit("private msg", msg);
Any suggestions?有什么建议么?
Finally, I found the answer.最后,我找到了答案。
I am still trying to figure out the reason for this, but on the server, every new connection has 2 different ID's:我仍在试图找出原因,但在服务器上,每个新连接都有 2 个不同的 ID:
io.on("connection", (socket) => {...
"socket" has: “套接字”有:
To emit for a specific socket, the ID on this line:要为特定套接字发出,此行上的 ID:
io.to(socketId).emit("private msg", msg);
Needs to be the socket.id , and not the socket.client.id.需要是socket.id ,而不是 socket.client.id。
I was not able to find anything related to why every socket has 2 different ID's.我找不到任何与为什么每个套接字都有 2 个不同的 ID 相关的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.