socket.io - broadcast to certain users

Viewed 10732

I need to build twosome chat, using websockets (socket.io + node.js). So, the simple example to broadcast message to all users:

socket.on('user message', function (msg) {
    socket.broadcast.emit('user message', socket.nickname, msg);
  });

But how can I broadcast it from certain user to certain user?

2 Answers

You can use the socket.join(...) function to provide groups:

socket.on('init', function(user) {
  if (user.type == 'dog') {
    socket.join('dogs');
  }
  else {
    socket.join('cats');
  }
});

...

io.to('dogs').emit('food', 'bone'); // Only dogs will receive it
io.to('cats').emit('food', 'milk'); // Only cats will receive it
Related