繁体   English   中英

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

[英]Sending messages to multiple rooms using Socket.io?

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

发送到 1 个房间:

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

发送到N个房间:

io.sockets.in(room1, room2, roomN).emit("id", {})

是的,可以一起发射到多个房间。 测试

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

那是因为当您使用toin您将房间附加到要定位的房间列表中。 源代码(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;
};

sockets.in方法只接受一个房间作为参数,因此要向多个房间广播,您必须在发射之间重置房间。 这样的事情应该工作:

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

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

更新:

从 Socket.IO v4.0.0 开始,现在可以发射到多个房间。 根据文档,这是使用修改后的to()方法应该如何完成的:

io.to(["room1", "room2", "room3"]).emit(/* ... */);

socket.to(["room1", "room2", "room3"]).emit(/* ... */);

链接到文档本身: https : //socket.io/blog/socket-io-4-release/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM