What's the difference between io.sockets.emit and broadcast?

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?

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
});
92641 次浏览

io.sockets.emit将发送给所有客户

socket.broadcast.emit will send the message to all the other clients except the newly created connection

这篇 Socket.IO Wiki 文章将帮助每个人阅读这个问题:

最近的备忘单也可以在这里看到:

https://socket.io/docs/v4/emit-cheatsheet

socket.broadcast.emit()的行为类似于 io.sockets.emit,但是 发射到所有连接的套接字,它将发射到所有连接的 套接字,除了它被调用的那个套接字。因此在这个例子中,套接字 被 socket引用将不会接收事件。

Scenario:1:- By the use of io.sockets.emit 详细图解:-io.sockets.胚胎发射

Here Every Socket gets the Message including Initiator.

  // BY IO>SOCKETS>EMIT
io.sockets.emit('MyChannelBroadcast',
{
owner:"Anshu Ashish",
clientCount:clients,
message:"Welcome All"
}
);

场景: 2:-通过使用 < strong > socket.Broadcast.sent 详细关系图:-socket.Broadcast

在这里每个插座都得到消息,除了一个即 发起人

    // BY SOCKET>BROADCAST>EMIT
socket.broadcast.emit('BroadCastExceptMe',{data:"HAVE A NICE DAY"});

结论:-现在完全取决于我们的业务需求,哪一个更好。

为了简单起见,考虑下面的例子: 有两个客户端 client A客户 B服务器 用于响应客户端发出的某些事件。

socket.brodcast.emit()

客户端 A 发送事件 In this case, the server will not send the event back to 客户 A but it will send the events to all others connected sockets. So in this case only the 客户 B will get the event response

io.emit()

客户端 A 发送事件,服务器将把应答事件发送到所有连接的套接字 客户 A客户 B