我很难找到io.sockets.clients()
上的文档,这样我就可以检索连接的客户端id、用户名等。当我alert(io.sockets.clients().length.toString());
时,它会给我正确的数字,但我需要找到数组的结构。有没有一种方法可以让我在不知道结构的情况下计算出数组?很像php的print_r()
?
到目前为止的代码:
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)
}
});
我在"switchRoom"启动后收到此错误
/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)
您是在客户端(浏览器中)还是在服务器端执行此操作?您提到使用alert
,但我不知道客户端有clients()
方法可以满足您的需要。
在服务器端,clients()
返回由以下方法定义的Socket
的数组:
/**
* Retrieves all clients as Socket instances as an array.
*
* @api public
*/
SocketNamespace.prototype.clients = function (room) {
var room = this.name + (room !== undefined ?
'/' + room : '');
if (!this.manager.rooms[room]) {
return [];
}
return this.manager.rooms[room].map(function (id) {
return this.socket(id);
}, this);
};
Node.js控制台和带有开发工具的浏览器提供了一个允许调试的console
对象;一般来说,你可以调用console.log(something)
,其中something
几乎是任何东西;在对象的情况下,将以某种方式枚举对象的详细信息。
[编辑]
由于您已经在使用socket.set
来存储用户名,也许您可以尝试以下操作:
// server
socket.on('connection', function(socket) {
...
socket.on('disconnect', function() {
socket.get('username', function (err, name) {
socket.broadcast.emit('disconnected', name);
});
});
...
});
// client
socket.on('connect', function () {
...
socket.on('disconnected', function(name) {
console.log(name + " disconnected.");
});
...
});