Socket.io房间的broadcast.to和sockets.in之间的区别


102

Socket.io的自述文件包含以下示例:

    var io = require('socket.io').listen(80);

    io.sockets.on('connection', function (socket) {
      socket.join('justin bieber fans');
      socket.broadcast.to('justin bieber fans').emit('new fan');
      io.sockets.in('rammstein fans').emit('new non-fan');
    });

socket.broadcast.to()和之间有什么区别io.sockets.in()


14
示例数据的投票
dave 2015年

Answers:


122

socket.broadcast.to广播在给定房间中所有的插座,除外到它被调用而插座io.sockets.in广播在给定房间内的所有插座。


1
频道与房间有何不同?
vsync

6
没有。同一件事的不同名称。
mike_hornbeck

socket.io使用术语“房间”代替“通道”。房间/通道不要与socket.io中的名称空间混淆。我更新了答案以使用正确的术语。
Daniel Baulig 2013年

40

Node.js一直是我真正感兴趣的东西,我在一个项目中使用它来制作多人游戏。

io.sockets.in().emit()socket.broadcast.to().emit()是我们在Socket.io的房间(https://github.com/LearnBoost/socket.io/wiki/Rooms)中使用的主要两种发出方法。房间允许对连接的客户端进行简单分区。这允许将事件与连接的客户端列表的子集一起发出,并提供一种简单的方法来管理它们。

它们使我们能够管理连接的客户端列表的子集(我们称为房间),并具有类似的功能,例如main socket.io函数io.sockets.emit()socket.broadcast.emit()

无论如何,我将尝试给出示例代码以及注释以进行解释。看看是否有帮助;

Socket.io房间

i)io.sockets.in()。emit();

/* Send message to the room1. It broadcasts the data to all 
   the socket clients which are connected to the room1 */

io.sockets.in('room1').emit('function', {foo:bar});

ii)socket.broadcast.to()。emit();

io.sockets.on('connection', function (socket) {
    socket.on('function', function(data){

        /* Broadcast to room1 except the sender. In other word, 
            It broadcast all the socket clients which are connected 
            to the room1 except the sender */
        socket.broadcast.to('room1').emit('function', {foo:bar});

    }
}

套接字

i)io.sockets.emit();

/* Send message to all. It broadcasts the data to all 
   the socket clients which are connected to the server; */

io.sockets.emit('function', {foo:bar});

ii)socket.broadcast.emit();

io.sockets.on('connection', function (socket) {
    socket.on('function', function(data){

        // Broadcast to all the socket clients except the sender
        socket.broadcast.emit('function', {foo:bar}); 

    }
}

干杯


35

更新2019:socket.io是一个特殊的模块,它使用websockets然后回退到http请求轮询。仅用于websocket:对于客户端,请使用本机websocket;对于node.js,请使用ws或此库。

简单的例子

语法在socketio中令人困惑。此外,每个套接字都将使用id自动连接到自己的房间socket.id(这是在socketio中私人聊天的工作方式,他们使用房间)。

发送给发件人,没有其他人

socket.emit('hello', msg);

发送给“我的房间”房间中所有人,包括发件人(如果发件人在房间中)

io.to('my room').emit('hello', msg);

发送给“我的房间”房间中发件人(如果发件人在房间内)以外的所有人

socket.broadcast.to('my room').emit('hello', msg);

发送给每个房间中的每个人包括发件人

io.emit('hello', msg); // short version

io.sockets.emit('hello', msg);

仅发送到特定的套接字(私人聊天)

socket.broadcast.to(otherSocket.id).emit('hello', msg);

如何找到otherSocket.id。在哪里设置呢?
伊曼·马拉希

@ImanMarashi您需要做的就是获取另一个套接字对象,然后访问它的id属性。 otherSocket.on('connect',()=> { console.log(otherSocket.id); });
K-SO的毒性在增加。

太棒了!io.to('my room')。emit('hello',msg); 它对我有帮助:)
iamkdblue

@ImanMarashi可以将otherSocket.id保存在外部数组或对象中。并稍后从被调用的任何套接字中访问它。
K-SO的毒性在增加。

2
io.on('connect', onConnect);

function onConnect(socket){

  // sending to the client
  socket.emit('hello', 'can you hear me?', 1, 2, 'abc');

  // sending to all clients except sender
  socket.broadcast.emit('broadcast', 'hello friends!');

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

  // 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)");

  // sending to all clients in 'game' room, including sender
  io.in('game').emit('big-announcement', 'the game will start soon');

  // sending to all clients in namespace 'myNamespace', including sender
  io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon');

  // sending to a specific room in a specific namespace, including sender
  io.of('myNamespace').to('room').emit('event', 'message');

  // sending to individual socketid (private message)
  io.to(`${socketId}`).emit('hey', 'I just met you');

  // WARNING: `socket.to(socket.id).emit()` will NOT work, as it will send to everyone in the room
  // named `socket.id` but the sender. Please use the classic `socket.emit()` instead.

  // sending with acknowledgement
  socket.emit('question', 'do you think so?', function (answer) {});

  // sending without compression
  socket.compress(false).emit('uncompressed', "that's rough");

  // sending a message that might be dropped if the client is not ready to receive messages
  socket.volatile.emit('maybe', 'do you really need it?');

  // specifying whether the data to send has binary data
  socket.binary(false).emit('what', 'I have no binaries!');

  // sending to all clients on this node (when using multiple nodes)
  io.local.emit('hi', 'my lovely babies');

  // sending to all connected clients
  io.emit('an event sent to all connected clients');

};

您可以提供附带代码的说明吗?通常,仅仅提供代码是不被接受的。但是,我看到您的代码受到了很好的评论:)
MBorg

1

在Socket.IO 1.0中,.to()和.in()相同。房间中的其他人也会收到该消息。客户端发送它不会收到该消息。

签出源代码(v1.0.6):

https://github.com/Automattic/socket.io/blob/a40068b5f328fe50a2cd1e54c681be792d89a595/lib/socket.js#L173


由于.to(),in是相同的,那么当我创建一个名称与某些套接字的ID完全相同的房间时会发生什么。socket.broadcast.to(socketid)例如,那会做什么?
古斯特·范·德·沃尔
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.