0
votes

I know how to send a message localy and to broadcast socket.broadcast.emit() function:- all the connected clients receive the same message.

Now, I would like to know how to send a private message to a particular client, I mean one socket for a private chat between 2 person (Client-To-Client stream). Thanks.

2

2 Answers

1
votes

server side:

var usersConnectedTo = {};

io.on('connection', function(socket){

socket.on('set_socketid', function(user){
    usersConnectedTo[user] = socket.id; // if usersConnectedTo[user] is undefined
});
socket.on('private_message', function(private_msg){
    var id = usersConnectedTo[private_message.user];
    io.to(id).emit('private_message', private_message.msg);
  });
});

client side:

io.emit('user', user1+user2); // user should be such that when A connects to B for 
// first time or B connects to B for first time, it should always return same user. 

io.emit('private_message', {
    user: user1+user2,
    msg: 'private_msg'
});

usersConnectedTo variable stores the socketid for each private chat.

In order to save different socket.id for chat between (A, B) and (A, C), socket.id is saved as AB and AC.

user and private_message should be emitted syncronously.

0
votes

SURE: Simply,

This is what you need :

 io.to(socket.id).emit("event", data);

whenever a user joined to the server,socket details will be generated including ID.This is the ID really helps to send a message to particular people.

first we need to store all the socket.ids in array,

  var people={};

  people[name] =  socket.id;

here name is the reciever name. Example:

 people["trojan"]=2387423cjhgfwerwer23;

So, now we can get that socket.id with the reciever name whenever we are sending message:

for this we need to know the recievername.You need to emit reciever name to the server.

final thing is:

  socket.on('chat message', function(data){
  io.to(people[data.reciever]).emit('chat message', data.msg);
  });

Hope this works well for you.!!Good Luck