Sending messages to multiple rooms using Socket.io?

你说的曾经没有我的故事 提交于 2019-12-21 05:47:07

问题


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", {})

回答1:


The sockets.in method only accepts one room as an argument, so to broadcast to multiple rooms you would have to reset the room, in between emissions. Something like this should work:

['room1', 'room2', 'room3'].forEach(function(room){
    io.sockets.in(room).emit("id", {});
});



回答2:


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;
};



回答3:


Updated as of Socket.IO v2.0.3

// sending to all clients in 'game1' and/or in 'game2' room, except sender
socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");

https://socket.io/docs/emit-cheatsheet/



来源:https://stackoverflow.com/questions/18304236/sending-messages-to-multiple-rooms-using-socket-io

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!