I was looking at answers here How to send a message to a particular client with socket.io, specifically the 2nd one, which recommends using rooms for 1 to 1 chat. I did the following on my server:
io.on('connection', (socket) => {
socket.on('message', (data) => {
socket.join(data.to);
io.sockets.in(data.to).emit('send_message', { message: data.message, to: data.to });
});
});
And on my client I have this:
const sendMessage = (e) => {
e.preventDefault();
io.emit('message', { to: friend._id, from: currentUserID, message }); // here friend._id
// will be currentUserID in the 2nd user's browser. Which makes it so they join different rooms
setMessage('');
}; // this function runs on form submission.
io.on('send_message', (message) => {
// do stuff with the message
});
But my users won't join the same room. Each one joins a room identified by the other user's id (friend._id). So they're unable to see each other's messages. In the answer from above they do a similar thing, just with each user's emails instead, which should result in the same issue I have as far as I understad.