node.jswebsocketsocket.iochatroom

socket.io rooms difference between to and in


I'm trying to get myself acquainted with socket.io and node. https://socket.io/docs/rooms-and-namespaces/

This is my reference.

var socketIO = require('socket.io')(http);
 socketIO.on('connection', function(socket) { 
 socket.join(data.room);})
 socketIO.in(users[key].room).emit('newmsg', data); 
        socketIO.to(users[key].room).emit('newmsg', data); 

Here the code with socketIO.in gives output whereas socketIO.to doesn't
But as per their documentation in and to should return the same o/p. Someone please explain to me the critical difference b/w them.


Solution

  • Right in the socket.io doc:

    namespace.in(room)
    
    Synonym of namespace.to(room).
    

    So, .to() and .in() are the same.


    And, if you look in the code, you see this:

    Namespace.prototype.to =
    Namespace.prototype.in = function(name){
      if (!~this.rooms.indexOf(name)) this.rooms.push(name);
      return this;
    };
    

    So, both .to() and .in() run the exact same code so any difference you think you are seeing is not because of the difference between calling .to() or .in(). It must be due to something else. You'd have to show us a reproducible set of code that shows some difference for us to help you debug that.