-1

Here is my way to implement one to one chat with two users using socket.io rooms

USERS TABLE
------------
id name
1  bar
2  foo
3  clay

Let's say if user bar want to chat with foo

socket.join(1);
socket.join(2);

Upon sending messages opposite user id is used as receiver id so that I can easily send messages

socket.on('chat', function(data){
//data object contains other user id as receiver id
  io.sockets.in(data.receiverId).emit('chat',{
                message:data.message,
                created_at:new Date()
            });
});

This works fine but I need one more condition at a time a user can chat only once to the user.

if clay send a message to bar that message can be readable by bar, so how can I avoid this problem

shamon shamsudeen
  • 5,466
  • 17
  • 64
  • 129

2 Answers2

0

There is no way to Send Message to specific person in the room. When you emit any event in the room, It is emit for everyone who is connected in the room.
Here, I give you an example to join in the room and how to emit event in that room.

// Server Side
// connection is inbuilt event of socket
io.on('connection', (socket)=>{
    // Every time it generates new id when user is connected to socket. 
    console.log(socket.id, "is connected");

    socket.join("RoomName");

    // Here, message is an event name and you can pass your data in second parameter
    io.in("RoomName").emit("message", {"data": "Hello All!"});
}
Leet Hudka
  • 226
  • 3
  • 16
0

Try to use to to the target socket client id

// sending to individual socketid (private message)
io.to(`${socketId}`).emit('hey', 'I just met you');

Referenece: https://socket.io/docs/emit-cheatsheet/

Di Wang
  • 407
  • 1
  • 5
  • 13