0

I'm trying to create a basic chat application. I'm using socket.io and I'm having a hard time figuring out how should I handle user to user communication.

I read here few of the answers: How to send a message to a particular client with socket.io

but I'm still confused, let's say I have 3 users, A, B and C. I want A to speak to B, and I want C to speak to B. Of course, A should not see B and C messages to each other, and vice versa.

This socket rooms idea seems great, but it seems to me like anyone can join the "room" and see each others messages.

I'm pretty confused, and not sure how I should approach this. I read another answer, which is each user will have a socket, so I can use the socket to send message. So something like this:

A user ID -> socket number 1
B user ID -> socket number 2
C user ID -> socket number 3

So when A sends message to be, it will send it from A's socket to B's socket.

But I'm not sure I got that right.

John Doah
  • 1,839
  • 7
  • 25
  • 46

1 Answers1

1

A 'room' is just a container, and not (necessarily) to be thought of as a chat-room. If you only want A-B and C-B to communicate with one another, then put them in two separate rooms. Remember, API does not allow clients to join arbitrary rooms. It is the server that determines which rooms to put client sockets into.

Going by your use-case, when A signals to the server that they would like to communicate with B, set up a room on the server-side, and put both, A and B server-side sockets into that room. Then, when A sends a chat message, you can look up the various rooms that A belongs to, and decide which room(s) to broadcast (io.in(...).emit(...)) that message to.

Instead, if you really want peer-to-peer communication, perhaps socket.io isn't the best tool for the job? It is still absolutely doable, but you are introducing an additional hop.
In this case, you could have your server receive a message from A (which also contains the recipient's identifier), determine who the recipient is, and send the message directly to that socket (every socket belongs to a 'room' whose name is the same as socket.id)

Guru Prasad
  • 4,053
  • 2
  • 25
  • 43