walolinux walolinux - 3 months ago 14
Node.js Question

Socketio 1.0 get attributes from all clients

I am currently working on a simple socketio application in which i am sending some parameters to envents and i am storing them into each socket.

socket.on('add user', function (data) {
if (addedUser) return;

// we store the username in the socket session for this client.
socket.nickname = data.nickname;
socket.userId = data.userId;
...


Then i am getting all socketio clients using var io.engine.clients and i am trying to obtain that parameters in other event like this:

socket.on('new message', function (data) {

var clientsRoom = io.engine.clients;

for(var c in clientsRoom){
console.log(" Client: " + c.userId); //Error
console.log(" Client: " + c); //outputs the socket ID
console.log(" Client: " + c['userId']); //Error
}
...


but i am unable to get my userID previously stored for all sockets. ┬┐What am i doing wrong?

Thanks.

Answer

Instead of io.engine.clients, you should use io.sockets.sockets (they aren't the same, socket.io adds an extra layer on top of engine.io). Also make sure that you treat it as an object, not an array:

var clientsRoom = io.sockets.sockets;

for (var id in clientsRoom) {
  var c = clientsRoom[id];
  console.log(" Client: " + c.userId);
  console.log(" Client: " + id);
}
Comments