Socket.io rooms difference between broadcast.to and sockets.in

node.jssocket.io

node.js Problem Overview


Socket.io's readme contains the following example:

    var io = require('socket.io').listen(80);

    io.sockets.on('connection', function (socket) {
      socket.join('justin bieber fans');
      socket.broadcast.to('justin bieber fans').emit('new fan');
      io.sockets.in('rammstein fans').emit('new non-fan');
    });

What's the difference between socket.broadcast.to() and io.sockets.in()?

node.js Solutions


Solution 1 - node.js

socket.broadcast.to broadcasts to all sockets in the given room, except to the socket on which it was called while io.sockets.in broadcasts to all sockets in the given room.

Solution 2 - node.js

Node.js was something I was really interested forawhile and I used it in one of my project to make a multiplayer game.

io.sockets.in().emit() and socket.broadcast.to().emit() are the main two emit methods we use in Socket.io's Rooms (https://github.com/LearnBoost/socket.io/wiki/Rooms) Rooms allow simple partitioning of the connected clients. This allows events to be emitted with to subsets of the connected client list, and gives a simple method of managing them.

They allow us to manage the subsets of the connected client list(which we call rooms) and have the similiar functionalities like the main socket.io functions io.sockets.emit() and socket.broadcast.emit().

Anyway I'll try to give the example codes with the comments to explain. See if it helps;

Socket.io Rooms

i) io.sockets.in().emit();

/* Send message to the room1. It broadcasts the data to all 
   the socket clients which are connected to the room1 */

io.sockets.in('room1').emit('function', {foo:bar});

ii) socket.broadcast.to().emit();

io.sockets.on('connection', function (socket) {
    socket.on('function', function(data){

		/* Broadcast to room1 except the sender. In other word, 
            It broadcast all the socket clients which are connected 
            to the room1 except the sender */
		socket.broadcast.to('room1').emit('function', {foo:bar});

    }
}

Socket.io

i) io.sockets.emit();

/* Send message to all. It broadcasts the data to all 
   the socket clients which are connected to the server; */

io.sockets.emit('function', {foo:bar});

ii) socket.broadcast.emit();

io.sockets.on('connection', function (socket) {
    socket.on('function', function(data){

		// Broadcast to all the socket clients except the sender
    	socket.broadcast.emit('function', {foo:bar}); 

    }
}

Cheers

Solution 3 - node.js

Update 2019: socket.io is a special module which uses websockets and then fallsback to http request polling. For just websockets: for the client use native websockets and for node.js use ws or this library.

Simple example

The syntax is confusing in socketio. Also, every socket is automatically connected to their own room with the id socket.id (this is how private chat works in socketio, they use rooms).

Send to the sender and noone else

socket.emit('hello', msg);

Send to everyone including the sender(if the sender is in the room) in the room "my room"

io.to('my room').emit('hello', msg);

Send to everyone except the sender(if the sender is in the room) in the room "my room"

socket.broadcast.to('my room').emit('hello', msg);

Send to everyone in every room, including the sender

io.emit('hello', msg); // short version

io.sockets.emit('hello', msg);

Send to specific socket only (private chat)

socket.broadcast.to(otherSocket.id).emit('hello', msg);

Solution 4 - node.js

io.on('connect', onConnect);

function onConnect(socket){

  // sending to the client
  socket.emit('hello', 'can you hear me?', 1, 2, 'abc');

  // sending to all clients except sender
  socket.broadcast.emit('broadcast', 'hello friends!');

  // sending to all clients in 'game' room except sender
  socket.to('game').emit('nice game', "let's play a game");

  // sending to all clients in 'game1' and/or in 'game2' room, except sender
  socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");

  // sending to all clients in 'game' room, including sender
  io.in('game').emit('big-announcement', 'the game will start soon');

  // sending to all clients in namespace 'myNamespace', including sender
  io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon');

  // sending to a specific room in a specific namespace, including sender
  io.of('myNamespace').to('room').emit('event', 'message');

  // sending to individual socketid (private message)
  io.to(`${socketId}`).emit('hey', 'I just met you');

  // WARNING: `socket.to(socket.id).emit()` will NOT work, as it will send to everyone in the room
  // named `socket.id` but the sender. Please use the classic `socket.emit()` instead.

  // sending with acknowledgement
  socket.emit('question', 'do you think so?', function (answer) {});

  // sending without compression
  socket.compress(false).emit('uncompressed', "that's rough");

  // sending a message that might be dropped if the client is not ready to receive messages
  socket.volatile.emit('maybe', 'do you really need it?');

  // specifying whether the data to send has binary data
  socket.binary(false).emit('what', 'I have no binaries!');

  // sending to all clients on this node (when using multiple nodes)
  io.local.emit('hi', 'my lovely babies');

  // sending to all connected clients
  io.emit('an event sent to all connected clients');

};

Solution 5 - node.js

In Socket.IO 1.0, .to() and .in() are the same. And others in the room will receive the message. The client sends it won't receive the message.

Check out source code (v1.0.6):

https://github.com/Automattic/socket.io/blob/a40068b5f328fe50a2cd1e54c681be792d89a595/lib/socket.js#L173

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionknexView Question on Stackoverflow
Solution 1 - node.jsDaniel BauligView Answer on Stackoverflow
Solution 2 - node.jsGokhan TankView Answer on Stackoverflow
Solution 3 - node.jsbasickarlView Answer on Stackoverflow
Solution 4 - node.jssun1211View Answer on Stackoverflow
Solution 5 - node.jsJames J. YeView Answer on Stackoverflow