Socket.io:检查与套接字ID的连接状态

fra*_*zon 7 javascript node.js socket.io

我有一个连接的套接字ID.我可以在另一个的函数处理程序中获取该连接的状态吗?

像这样的东西:

io.sockets.on('connection', function(socket) {
    /* having the socket id of *another* connection, I can
     * check its status here.
     */
    io.sockets[other_socket_id].status
}
Run Code Online (Sandbox Code Playgroud)

有办法吗?

Riw*_*els 14

对于高于1.0的版本,请查看Karan Kapoor的答案.对于旧版本,您可以访问任何连接的套接字io.sockets.sockets[a_socket_id],因此如果您在其上设置了状态变量,则io.sockets.sockets[a_socket_id].status可以使用.

首先,您应该检查套接字是否确实存在,它还可以用于检查连接/断开状态.

if(io.sockets.sockets[a_socket_id]!=undefined){
  console.log(io.sockets.sockets[a_socket_id]); 
}else{
  console.log("Socket not connected");
}
Run Code Online (Sandbox Code Playgroud)


Kar*_*oor 6

截至今天,2015年2月,此处列出的方法都不适用于当前版本的Socket.io(1.1.0).所以在这个版本中,这就是它对我有用的方式:

var socketList = io.sockets.server.eio.clients;
            if (socketList[user.socketid] === undefined){
Run Code Online (Sandbox Code Playgroud)

io.sockets.server.eio.clients是一个包含所有实时套接字ID列表的数组.因此,使用if语句中的代码检查特定套接字ID是否在此列表中.