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 });
Simply said Each socket emits its msg to a server(io is an instance of server) and server, in turn, emits it to all connected sockets.
We can send the message to all the connected clients, to clients on a namespace and clients in a particular room. To broadcast an event to all the clients, we can use the io. sockets. emit method. Note − This will emit the event to ALL the connected clients (event the socket that might have fired this event).
emit() to send a message to all the connected clients. This code will notify when a user connects to the server. io.on("connection", function(socket) { io.emit(“user connected”); });
Key Differences between WebSocket and socket.ioIt provides the Connection over TCP, while Socket.io is a library to abstract the WebSocket connections. WebSocket doesn't have fallback options, while Socket.io supports fallback. WebSocket is the technology, while Socket.io is a library for WebSockets.
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:
https://socket.io/docs/v4/emit-cheatsheet
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With