Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 }); 
like image 890
swiecki Avatar asked Apr 26 '12 23:04

swiecki


People also ask

What is difference between Socket emit and io emit?

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.

What is io sockets emit?

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).

What is emit and on in Socket?

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”); });

What is difference between Socket and io?

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.


1 Answers

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

like image 142
Jayantha Lal Sirisena Avatar answered Sep 22 '22 07:09

Jayantha Lal Sirisena