Reputation: 437
I have a chat app with node.js, socket io, and 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!)
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. The only issue is with the ones using:
io.to(socketId).emit("private msg", msg);
Any suggestions?
Upvotes: 0
Views: 472
Reputation: 437
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:
io.on("connection", (socket) => {...
"socket" has:
To emit for a specific socket, the ID on this line:
io.to(socketId).emit("private msg", msg);
Needs to be the socket.id, and not the socket.client.id.
I was not able to find anything related to why every socket has 2 different ID's.
Upvotes: 2