I’m having a heck of a time finding documentation on io.sockets.clients() so I can retrieve the connected clients id, username, etc. When I alert(io.sockets.clients().length.toString()); it gives me the correct number, but I need to find the structure of the array. Is there a way I can figure out the array without knowing the structure? Much like php’s print_r()?
Code so far:
socket.on('switchRoom', function(newroom){
var clients = io.sockets.clients();
socket.emit('users', clients);
});
socket.on('users', function(usernames) {
for(var client in usernames) {
console.log(usernames[client].id + ' disconnected: ' + usernames[client].disconnected)
}
});
I receive this error after ‘switchRoom’ is fired
/home/ed/socket/chat/node_modules/socket.io/lib/parser.js:81
data = JSON.stringify(ev);
^
TypeError: Converting circular structure to JSON
at Object.stringify (native)
at Object.encodePacket (/home/ed/socket/chat/node_modules/socket.io/lib/parser.js:81:19)
at Socket.packet (/home/ed/socket/chat/node_modules/socket.io/lib/socket.js:202:21)
at Socket.emit (/home/ed/socket/chat/node_modules/socket.io/lib/socket.js:351:15)
at Socket.<anonymous> (/home/ed/socket/chat/app.js:58:10)
at Socket.$emit (events.js:64:17)
at SocketNamespace.handlePacket (/home/ed/socket/chat/node_modules/socket.io/lib/namespace.js:331:20)
at Manager.onClientMessage (/home/ed/socket/chat/node_modules/socket.io/lib/manager.js:436:38)
at WebSocket.onMessage (/home/ed/socket/chat/node_modules/socket.io/lib/transport.js:387:20)
at Parser.<anonymous> (/home/ed/socket/chat/node_modules/socket.io/lib/transports/websocket/hybi-07-12.js:38:10)
Are you doing this on the client side (in the browser) or on the server side? You mention using
alert, but I’m not aware of aclients()method on the client side that does what you want.On the server side,
clients()returns an array ofSockets as defined by this method:The Node.js console and browsers with dev tools provide a
consoleobject that allows debugging; generally, you can callconsole.log(something)wheresomethingpretty much anything; in the case of an object, the details of the object will be enumerated in one way or another.[Edit]
Since you’re already using
socket.setto store the username, perhaps you can try something like this: