2

I'm creating a chat with Socket.IO and Express to be able to chat one to one (private chat).

The main problem is: I want to send a private message to a socket.id, but I want that the sender receives the same message that he sent to the receiver.

module.exports = (io, socket) => {
  socket.on('send private message', async (msg) => {
    const emitterUser = // mongoose query to get the emitter
    const receiverUser = // mongoose query to get the receiver

    // sending to individual socketid (private message)
    socket.to(receiverUser.socketId).emit('receiver private message', msg); // <- sending to the receiver
    socket.emit('sender private message', msg);// <- sending to the sender
  });
}  

I would like to know if is there a better way to do it to create a private chat or if I'm going to the wrong direction.

Victor
  • 724
  • 3
  • 12
  • 32

1 Answers1

-1

You can use the function GROUP of socket-io docs: https://socket.io/docs/server-api/

update

io.on('connection', function(socket){
  console.log('people connect: ' + socket.id);

  // listen create and join room from client
  socket.on('create-room', function(nameroom){
    socket.join(nameroom); // if room not exists create and join to room, if room exists client will join to room
    console.log(nameroom);

    // get all name room
    var array=[];
    for(r in socket.adapter.rooms){
      array.push(r);
    }
    console.log(array);
  });

  // listen message from client
  socket.on('client-send-message', function(message){
    io.sockets.in('some-name-room').emit('key-chat', message);
  });
});
Chanh
  • 433
  • 3
  • 12
  • Do you mean 'rooms'? I'm trying to figure it out how can I create a room for only 2 users and join them simultaneously. Is it possible to you to demonstrate something about it? Thanks! – Victor Jul 23 '18 at 02:12
  • You can create a room and connect two people into one room. Or simply when each connection is made, each socket itself is a room (the main room is the socketId of the same connection). sorry my english is not good – Chanh Jul 23 '18 at 03:00
  • So.. what is the idea? How can I connect two people in a room simultaneously? That's a thing that I did not find in the docs. – Victor Jul 24 '18 at 00:31