0

I have tried this link: Socket.IO subscribe to multiple channels.

I have used method socket.on and io.emit for request and response respectively.

Currently I have facing issue that I got response to all users.
I want to just notify for particular user.

Community
  • 1
  • 1
Ravi
  • 1
  • 2

1 Answers1

1

When a user connects, it should send a message to the server with a username which has to be unique.

A pair of username and socket should be stored in an object like this:

var users = {
   'userA@foobar.com': [socket object], // USER SOCKET OBJECT
   'userB@foobar.com': [socket object], // USER SOCKET OBJECT
   'userC@foobar.com': [socket object]  // USER SOCKET OBJECT
}

On the client, emit an object to the server with the following data:

{
   to:[receiver's username],
   from:[the person who sent the message],
   message:[the message to be sent],
   //..other details..
}

On the server, listen for messages. When a message is received, emit the data to the receiver.

users[data.to].emit('new-message', data.message)

On the client, you will need to listen to new-message.

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328