使用Socket.io将消息发送到多个房间?

问题描述 投票:3回答:3

是否可以使用socket.io将消息发送到多个房间?

发送到1个房间:

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

发送到N个房间:

io.sockets.in(room1, room2, roomN).emit("id", {})
node.js socket.io channel
3个回答
5
投票

sockets.in方法只接受一个房间作为参数,因此要广播到多个房间,你必须在两个房间之间重置房间。这样的事情应该有效:

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

11
投票

是的,它可以完全发射到多个房间。来自the tests

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

那是因为当你使用toin时,你将房间附加到要定位的房间列表中。来自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;
};

2
投票

自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/

© www.soinside.com 2019 - 2024. All rights reserved.