How to send a message to a particular client with socket.io

前端 未结 6 1996
無奈伤痛
無奈伤痛 2020-11-28 00:02

I\'m starting with socket.io + node.js, I know how to send a message locally and to broadcast socket.broadcast.emit() function:- all the connected clients recei

6条回答
  •  抹茶落季
    2020-11-28 01:00

    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 receiver name. Example:

    people["ccccc"]=2387423cjhgfwerwer23;
    

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

    for this we need to know the receivername. You need to emit receiver name to the server.

    final thing is:

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

    Hope this works well for you.

    Good Luck!!

提交回复
热议问题