Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io - broadcast to certain users

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?

like image 923
Mark Pegasov Avatar asked Jul 14 '12 14:07

Mark Pegasov


People also ask

How many players can Socket.IO handle?

Once you reboot your machine, you will now be able to happily go to 55k concurrent connections (per incoming IP).


2 Answers

There are two possibilites :

1) Each socket has its own unique ID stored in socket.id. If you know the ID of both users, then you can simply use

io.sockets[id].emit(...)

2) Define your own ID (for example user's name) and use

socket.join('priv/John');

in connection handler. Now whenever you want send message only to John, you simply do

socket.broadcast.to('priv/John').emit(...)

Side note: the first solution provided cannot be scaled to multiple machines, so I advice using the second one.

like image 125
freakish Avatar answered Sep 23 '22 08:09

freakish


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
like image 42
Tibor Takács Avatar answered Sep 22 '22 08:09

Tibor Takács