What's the difference between io.sockets.emit and broadcast?
node.jssocket.ionode.js Problem Overview
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
});
node.js Solutions
Solution 1 - node.js
io.sockets.emit
will send to all the clients
socket.broadcast.emit
will send the message to all the other clients except the newly created connection
This Socket.IO Wiki post will help everyone reading this question:
The recent cheatsheet can also be viewed here:
Solution 2 - node.js
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 socket
will not receive the event.
Solution 3 - node.js
Scenario:1:- By the use of io.sockets.emit [Detailed Diagram:-io.sockets.emit][1]
> Here Every Socket gets the Message including Initiator.
// BY IO>SOCKETS>EMIT
io.sockets.emit('MyChannelBroadcast',
{
owner:"Anshu Ashish",
clientCount:clients,
message:"Welcome All"
}
);
Scenario:2:- By the use of socket.broadcast.emit [Detailed Diagram:-socket.broadcast.emit][2]
> Here Every Sockets are getting Message Except One i.e 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. [1]: https://i.stack.imgur.com/f52nC.jpg [2]: https://i.stack.imgur.com/b2ioe.jpg
Solution 4 - node.js
To make it quite simple, consider the following example: there are 2 clients client A, client B and a server we are using in response to certain event emitted by the client.
socket.brodcast.emit()
client A sends the event In this case, the server will not send the event back to client A but it will send the events to all others connected sockets. So in this case only the client B will get the event response
io.emit()
client A sends the event, the server will send the reply event to all the connected sockets both client A and client B