node.js io.sockets.emit 和广播有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10342681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the difference between io.sockets.emit and broadcast?
提问by swiecki
What's the difference between io.sockets.emit and socket.broadcast.emit? Is it only that broadcast emits to everyone BUT the socket that sends it?
io.sockets.emit 和 socket.broadcast.emit 有什么区别?只是广播向所有人发送,而不是发送它的套接字吗?
It seems like they can be used interchangeably:
似乎它们可以互换使用:
io.sockets.on('connection', function (socket) {
//these should do the same thing
io.sockets.emit('this', { receivers: 'everyone'});
socket.broadcast.emit('this', { receivers: 'everyone but socket'}); //emits to everyone but socket
socket.emit('this', { receivers: 'socket'}); //emits to socket
});
回答by Jayantha Lal Sirisena
io.sockets.emitwill send to all the clients
io.sockets.emit将发送给所有客户
socket.broadcast.emitwill send the message to all the other clients except the newly created connection
socket.broadcast.emit将消息发送给除新创建的连接之外的所有其他客户端
This Socket.IO Wiki post will help everyone reading this question:
回答by Karthic Rao
socket.broadcast.emit()behaves similar to io.sockets.emit, but instead
of emitting to all connected sockets it will emit to all connected
socket except the one it is being called on. So in this case the socket
referenced by socketwill not receive the event.
socket.broadcast.emit()行为类似于io.sockets.emit,但它不会向所有连接的套接字发射,而是向所有连接的套接字发射,除了被调用的套接字。所以在这种情况下引用的套接字socket将不会收到事件。
回答by Anshu Ashish
Scenario:1:- By the use of io.sockets.emitDetailed Diagram:-io.sockets.emit
场景:1:- 使用io.sockets.emit详解:-io.sockets.emit
Here Every Socket gets the Message including Initiator.
这里每个 Socket 都获取包括Initiator在内的 Message 。
// BY IO>SOCKETS>EMIT
io.sockets.emit('MyChannelBroadcast',
{
owner:"Anshu Ashish",
clientCount:clients,
message:"Welcome All"
}
);
Scenario:2:- By the use of socket.broadcast.emitDetailed Diagram:-socket.broadcast.emit
场景:2:- 使用socket.broadcast.emit 详图:-socket.broadcast.emit
Here Every Sockets are getting Message Except One i.e Initiator.
这里每个套接字都收到消息,即Initiator除外。
// BY SOCKET>BROADCAST>EMIT
socket.broadcast.emit('BroadCastExceptMe',{data:"HAVE A NICE DAY"});
Conclusion:- Now it will totally depends our business requirement that which one will be preferable.
结论:- 现在这完全取决于我们的业务需求,哪一个更可取。

