Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending messages to multiple rooms using Socket.io?

Is it possible to send messages to multiple rooms using socket.io?

Sending to 1 room:

io.sockets.in(room).emit("id", {})

Sending to N rooms:

io.sockets.in(room1, room2, roomN).emit("id", {})
like image 646
fusio Avatar asked Aug 18 '13 22:08

fusio


1 Answers

Yes, it's possible to emit to multiple rooms altogether. From the tests:

socket.on('emit', function(room){
  sio.in('woot').in('test').emit('a');
  sio.in('third').emit('b');
});

That's because when you use to or in you're appending the room to the list of rooms to be targeted. From the source code (lib/socket.js):

Socket.prototype.to =
Socket.prototype.in = function(name){
  this._rooms = this._rooms || [];
  if (!~this._rooms.indexOf(name)) this._rooms.push(name);
  return this;
};
like image 118
Ciro Costa Avatar answered Nov 15 '22 06:11

Ciro Costa