[英]What is the difference between - socket.broadcast.emit() and io.to(socketID).emit()?
Getting started with using socket.io library.开始使用 socket.io 库。 There is this use case where I need to broadcast to all connected clients except the sender.在这个用例中,我需要向除发件人以外的所有连接的客户端广播。 Therefore, I had used the socket.broadcast.emit() .因此,我使用了socket.broadcast.emit() 。
I came across another technique to achieve the same which was io.to(socketID).emit() .我遇到了另一种实现相同效果的技术io.to(socketID).emit() 。 From what I understand, this method emits to a room with an id = socketID (ideally this room would have just one client by default and the event will be emitted to this client).据我了解,此方法会发送到一个 id = socketID 的房间(理想情况下,这个房间默认只有一个客户端,并且事件将发送到该客户端)。
Is there any other functional difference between these two methods or can I use them interchangeably?这两种方法之间是否有任何其他功能差异,或者我可以互换使用它们吗?
Tried both ways, and they both seemed to work fine.尝试了两种方式,它们似乎都工作正常。 Just wanted to know if there's any difference and any limitations to either way of emitting.只是想知道这两种发射方式是否有任何区别和限制。
io.on("connection", (socket) => {
setInterval(() => {
socket.broadcast.emit('dummy_event', 'new_testing_21jan');
}, 5000);
}
and和
io.on("connection", (socket) => {
setInterval(() => {
io.to(socket.id).emit('dummy_event', 'new_testing_21jan');
}, 5000);
}
socket.broadcast.emit() broadcasts an event to all connected clients except the sender. socket.broadcast.emit()向除发送者之外的所有连接的客户端广播一个事件。
io.to(socketID).emit() is used to send event to specific socket by socket ID. io.to(socketID).emit()用于通过套接字ID向特定套接字发送事件。
Both can be used interchangeably in your use case, but io.to(socketID).emit() is more specific and useful for emitting events to specific clients.两者都可以在您的用例中互换使用,但io.to(socketID).emit()对于向特定客户端发出事件更为具体和有用。
socket.broadcast.emit() wants to send the event to all clients except the sender. socket.broadcast.emit()想要将事件发送给除发送者之外的所有客户端。
You can use io.in(roomName).emit() to send an event to all customers in a particular room.您可以使用io.in(roomName).emit()向特定房间中的所有客户发送事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.