broadcast.to和sockets.in之间Socket.io间差异broadcast.to和

2019-05-13 09:16发布

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()

Answer 1:

socket.broadcast.to广播在给定房间中的所有插槽, 除了在其上,而它被称为插座io.sockets.in广播在给定房间内的所有插座。



Answer 2:

Node.js的是我真的很感兴趣forawhile,我用它在我的项目,使多人游戏之一。

io.sockets.in().emit()socket.broadcast.to().emit()是主要的两个发射我们Socket.io的房间使用方法( https://github.com/LearnBoost/socket.io /维基/间 )客房允许连接的客户端的简单划分。 这使得与该连接的客户端列表的子集发出的事件,并给出了管理它们的简单方法。

他们让我们来管理连接的客户端列表的子集(我们称之为房间),并有similiar功能类似于主socket.io功能io.sockets.emit()socket.broadcast.emit()

无论如何,我会尽量给与评论的例子代码解释。 看看是否有帮助;

Socket.io客房

ⅰ)io.sockets.in()发射();

/* 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});

ⅱ)socket.broadcast.to()发射();

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

    }
}

Socket.io

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

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

    }
}

干杯



Answer 3:

更新2017:我建议开始寻找本地的WebSockets,因为他们以后将成为标准。

简单的例子

语法混乱中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);


Answer 4:

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

检查出的源代码(1.0.6):

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



文章来源: Socket.io rooms difference between broadcast.to and sockets.in
标签: socket.io