23

I want to "emit" a message to a particular client which is selected based on another message received in a different client, How do I do this?

I am thinking of joining each client to their own "room" and then broadcast. Is there a better way?

srinathhs
  • 1,998
  • 4
  • 19
  • 33

3 Answers3

39

UPDATE for socket.io version 1.0 and above

io.to(socketid).emit('message', 'whatever');

For older version:

You can store each client in an object as a property. Then you can lookup the socket based on the message:

var basket = {};

io.sockets.on('connection', function (socket) {
  socket.on("register", function(data) {
    basket[data.nickname] = socket.id;
  });
  socket.on("privmessage", function(data){
    var to = basket[data.to];
    io.sockets.socket(to).emit(data.msg);
  });
});

Not tested...but it should give you an idea

Francesco Laurita
  • 23,434
  • 8
  • 55
  • 63
  • 2
    How does it work with reddiss? I want to do the same thing but in a distributed load balanced environment. – budsiya May 12 '13 at 18:10
  • 2
    for the version 1.0, we need to use io.to(socketId).emit('pm', {}); like @Minho Lee said – Beast Jul 24 '14 at 12:26
  • @budsiya did you ever get it to work? I'm working on a similar problem, where I have multiple node processes running on a single server. – Daniel Que Aug 08 '14 at 00:26
  • @budsiya, you mean `redis` ? – Steel Brain Oct 07 '14 at 05:17
  • 1
    @Francesco This is very nice but you should expand the example, to help begginers grasp the concept. Or provide some links – slevin Dec 22 '15 at 13:57
  • socketId is actually a "room" now. so the client should subscribe for "roomUniqueId". and the server should know about it. no need to create an in-memory basket map. – liberborn Jun 20 '23 at 16:04
17

For socket.io version 1.0 use:

io.to(socketid).emit('message', 'whatever');
Yoav Kadosh
  • 4,807
  • 4
  • 39
  • 56
Minho Yi
  • 210
  • 2
  • 6
2

Emitting to a particular client using a socketID.

Server/ package: socket.io:

io.to(socketID).emit('testEvent', 'yourMessage');

Client/ package socket.io-client:

io.sockets.on('connection',(socket) => {
  socket.on("testEvent", data => {
    console.log(data);
  });
});

You can get access the socketID in the following manner:

io.on('connection', (socket, next) => {
    const ID = socket.id // id property on the socket Object
})

It is simply a property on the socket object

Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155