User presence in a socket.io 'room'

I have a system where users connect to a 'room' using Socket.io. Right now, when people load a page, the connection is made, and I can see how many people are connected to the given page (the URL dictating the room).

What I want is to be able to see metadata about the users on the page. I want to somehow know that Bob, Steve and Mary are looking at the page. Right now I only get the internal session Ids.

Server

io.on('connection', function(socket) {
  socket.on('viewPage', function(data, fn) {
    var roomName = 'page-' + data.url;
    socket.join(roomName);
    var room = io.sockets.adapter.rooms[roomName];
    console.log(Object.keys(room).length + ' users connected');
    fn({msg: 'Connected to room ' + roomName})
  })
});

Client

var socket = io();
socket = io.connect("http://localhost:5000");
socket.on('connect', function(data) {
  socket.emit('viewPage', {url: '/foo/bar'}, function(resp) {
    console.log(resp)
  });
});

From looking at the Socket.io docs there's join and so on, but I don't see any way of attaching metadata to the client connection.

How would I go about doing this? How can I ensure that I can see a list of connected users on a page?

Answers


Here's a very simple and unsafe way of passing metadata from the client to the Server and attaching it to the sockets using middleware. Usually only a session id is passed and the data is fetched on the server but I've cut some corners.

//Client
socket = io.connect("http://localhost:5000", {query: 'name=Bob'});

//Server
io.use(function (socket, next){
    var name = socket.handshake.query.name;
    socket._name = name;
    next();
});

Now you can do:

var room = io.sockets.adapter.rooms[roomName];
for (var key in room){
    console.log(room[key]._name);
}

Note you should handle multi-tabbing from the same user so you'd need to display only distinct _name values


Need Your Help

installing adMob banner gives me strange Mach-O linker error

ios objective-c admob banner

Hi i was trying to install adMob Ad in my app but xcode gives me this error

(2 n) Visual Cryptography using Python

python image algorithm encryption

I am trying to implement the simple algorithm mentioned on wikipedia to create a (2 n) secret sharing images using python.