How can I send a message to a particular client with socket.io?

Web Development

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 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

1
Answers

Replies

Ans:  You can try the below code to send a message to a particular client with socket.io.


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


Whenever the user joins into the server, the socket details will be generated including the ID. The UD is responsible for sending a message to a particular person or people.


The primary step is to store all the socket.ids in an array.


var person={};

person[name] =  socket.id;

The name will be the receiver name.

 
 

If you want to unleash your potential in this competitive field, please visit the Web Development course page for more information, where you can find the Web Development tutorials and Web Development frequently asked interview questions and answers as well.

 

This topic has been locked/unapproved. No replies allowed

Login to participate in this discussion.

Leave a reply

Before proceeding, please check your email for a verification link. If you did not receive the email, click here to request another.