1

I'm currently starting working with node.js and as a first little project have decided to code a little chat application. I am using socket.io and have followed the chat tutorial on http://socket.io/get-started/chat/ so far. Now I want to expand on the script, but I am stuck.

I fail to understand how (or if at all) socket.io is managing all connected clients on the server side. I can use the io.emit function to send a message to all connected users. But what if I want to send a message to one specific user?

I could of course "fake" it by sending the message to all clients and then on the client side check for an identifyer, etc. and only process the message if there is a match. But this would still send the message to everyone, and it could easily be circumvented by users with minimal JS knowledge.

The "filtering"/"targeting" needs to happen on the server side for security reasons. But I fail to see/understand how (or if at all) socket.io actually manages all client connections. Is there a way to get a list of all current connected clients? Can you interate over all connected clients in a loop? Can you assign custom identifiers/name to connections? And - as the practical application - can you then emit/send a message to a single connected user?

Konadi
  • 182
  • 11

1 Answers1

1

Every socket connection has a unique socket id assigned with it at the very first time when a new connection is established.You can emit the data using that particular id.

var socketId=socket.id;
socket.broadcast.to(socketId).emit("messageToReceiver",data);

Thus, you can send it to a particular person.

To get all the connected clients check this URL: Socket.IO - how do I get a list of connected sockets/clients?

Community
  • 1
  • 1
Subham
  • 1,414
  • 4
  • 17
  • 34