title: List of connected clients username using socket io
body: <p>I've made a chat client with different chat rooms in NodeJS, socketIO and Express. I am trying to display an updated list over connected users for each room.</p>
  <p>Is there a way to connect a username to an object so I could see all the usernames when I do:</p>
  <pre><code>var users = io.sockets.clients('room')
  </code></pre>
  <p>and then do something like this:</p>
  <pre><code>users[0].username
  </code></pre>
  <p>In what other ways can I do this?</p>
  <p><strong>Solved:</strong><br />
  This is sort of a duplicate, but the solution is not written out very clearly anywhere so I'd thought I write it down here. This is the solution of the <a href="https://stackoverflow.com/questions/6563885/socket-io-how-do-i-get-a-list-of-connected-sockets-clients">post</a> by <a href="https://stackoverflow.com/users/600539/andy-hin">Andy Hin</a> which was answered by <a href="https://stackoverflow.com/users/149260/mak">mak</a>. And also the comments in this post.</p>
  <p>Just to make things a bit clearer. If you want to store anything on a socket object you can do this:</p>
  <pre><code>socket.set('nickname', 'Guest');    
  </code></pre>
  <p>sockets also has a get method, so if you want all of the users do:</p>
  <pre><code>for (var socketId in io.sockets.sockets) {
      io.sockets.sockets[socketId].get('nickname', function(err, nickname) {
          console.log(nickname);
      });
  }
  </code></pre>
  <p>As <a href="https://stackoverflow.com/users/617839/alessioalex">alessioalex</a> pointed out, the API might change and it is safer to keep track of user by yourself. You can do so this by using the socket id on disconnect.</p>
  <pre><code>io.sockets.on('connection', function (socket) { 
      socket.on('disconnect', function() { 
          console.log(socket.id + ' disconnected');
          //remove user from db
      }
  });
  </code></pre>