title: socket.io: assure socket joins only one room at a time
body: <p>I'm working with socket.io 1.3.5. Clients can join rooms by sending a <code>join</code> message. Serverside code:</p>
  
  <pre class="lang-js prettyprint-override"><code>socket.on('join', function(room) {
    socket.join(room);
  });
  </code></pre>
  
  <p>Now I want to make sure that a client can only be in one room at a time. I want the client to automatically leave the current room if he joins a new one. This is my approach:</p>
  
  <pre class="lang-js prettyprint-override"><code>function leaveAllRooms(socket) {
      var rooms = socket.adapter.sids[socket.id];
      Object.keys(rooms).forEach(function(room) {
          if (room != socket.id) {
            socket.leave(room);
          }
      });
  }
  
  socket.on('join', function(room) {
    leaveAllRooms(socket);
    socket.join(room);
  });
  </code></pre>
  
  <p>Whenever a client want's to join a room, I call <code>leaveAllRooms</code> which calls <code>socket.leave()</code> for all rooms found in <code>socket.adapter.sids[socket.id]</code>, except the sockets own room.</p>
  
  <p>This solution seems to be working well, but I'm not sure if it is correct. In <a href="https://stackoverflow.com/questions/10895925/how-to-leave-all-rooms-that-the-socket-is-connected-to-at-one-go-in-node-js#comment28244797_10897966">another post's comment</a> it is mentioned that <code>io.sockets.manager.roomClients[socket.id]</code> can be used (instead of my <code>socket.adapter.sids[socket.id]</code>). I don't know which one is better. Is there a documentation about this somewhere? I find the docs at <a href="http://socket.io" rel="nofollow noreferrer">socket.io</a> quite sparse.</p>
  
  <p>In addition I wonder if this solution will work with namespaces or even multiple socket.io instances connected via Redis. Any advice?</p>