kisor
kisor

Reputation: 484

sending message to specific id in socket.io

this is the example code from official socket.io page about namespaces.

io.on('connection', function(socket){
  socket.on('say to someone', function(id, msg){
    socket.broadcast.to(id).emit('my message', msg);
  });
});

and my head is spinning how Id is sent from client side in 'say to someone' event what will be the unique id? how it is generated or we have to generate it??

Upvotes: 0

Views: 3097

Answers (1)

Akash Agarwal
Akash Agarwal

Reputation: 2520

Basically what you need to do is this:

users = {};
io.on('connection', function(socket){
    users[someKeyOfYourChoice] = socket.id;

    socket.on('say to someone', function(id, msg){
        io.to(users[requiredUserKey]).emit('my message', msg);
    });
});

You can store the socket.id of connected users in a hashmap and then use that id in the above function.

Upvotes: 2

Related Questions