0

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.

Julio
  • 1
  • 1
  • 1
  • Hi @Julio, i actually have an example exactly working same way, maybe you can check from there https://github.com/halilcakar/private-chat. It's not using emails tho – halilcakar Jun 24 '20 at 08:51
  • @HalilÇakar thank you. Your example showed me a way to figure it out. Basically in my server I save the connected sockets with their corresponding user id in an array. From there I can do private messaging. – Julio Jun 24 '20 at 20:59
  • I'm glad that it helped :) – halilcakar Jun 24 '20 at 20:59

0 Answers0