Socket.io: Does emitting messages send all data to all clients?

javascript, node.js, socket.io

Solution

No, what you're doing there would send a message to every single socket that is connected to the server, except the socket that is `socket`, if you want to broadcast to a specific room you would do

 io.sockets.in('some room name').broadcast('some data')

if you want to broadcast to everyone in a specific room except the sender if the sender is in that room you would do

 socket.broadcast.to('some room name').emit('some data');

First of all though you would probably need to create some rooms, in which case you would just do

someSocket.join('some room name')

Maybe something like this would help you out.

io.sockets.on('connection', function (socket) {
   // let everyone know i'm here
   socket.broadcast.emit('user connected');

   socket.on('join-data-request-room', function(){
       socket.join('data-request-room')
   })
});

Now you could do this

 io.sockets.in('data-request-room').broadcast('new data')

and it would send to each in that room, there are currently no one in that room, to add people in that room you would do something like this on the client (browser).

 io.emit('join-data-request-room')

Now and only now will that "client" be in the room `data-request-room`

I haven't used socket.io in months so there may be some better ways I don't know.

Problem

Question is geared towards understanding how socket.io works. If I have a server with multiple clients and the following function (pseudocode): ``` // Server-side socket.emit('data-request', { some large object }); ``` Does the server send the large data object to each of the clients or does it only send to clients that have a corresponding (function / event) ? ``` socket.on('data-request', function(data){blah blah blah}); ```

Original source