node.js Socket.io:用socket id检查连接状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16713495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Socket.io: check the status of a connection with the socket id
提问by franzlorenzon
I have a socket id of a connection. Can I get the status of that connection, inside the function handler of another one?
我有一个连接的套接字 ID。我可以在另一个连接的函数处理程序中获取该连接的状态吗?
Something like this:
像这样的东西:
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
}
Is there a way to do so?
有没有办法这样做?
回答by Riwels
For versions higher than 1.0, check Karan Kapoor answer.
For older versions, you can access any connected socket with io.sockets.sockets[a_socket_id], so if you've set a status variable on it, io.sockets.sockets[a_socket_id].statuswill work.
对于高于 1.0 的版本,请查看 Karan Kapoor 的答案。对于旧版本,您可以使用 访问任何连接的套接字io.sockets.sockets[a_socket_id],因此如果您在其上设置了状态变量,io.sockets.sockets[a_socket_id].status它将起作用。
First you should check if the socket really exists, and it can also be used to check connected/disconnected statuses.
首先你应该检查套接字是否真的存在,它也可以用来检查连接/断开状态。
if(io.sockets.sockets[a_socket_id]!=undefined){
console.log(io.sockets.sockets[a_socket_id]);
}else{
console.log("Socket not connected");
}
回答by Karan Kapoor
As of today, Feb, 2015, none of the methods listed here work on the current version of Socket.io (1.1.0). So on this version, this is how it works for me :
截至今天,2015 年 2 月,此处列出的方法均不适用于当前版本的 Socket.io (1.1.0)。所以在这个版本上,这对我来说是这样的:
var socketList = io.sockets.server.eio.clients;
if (socketList[user.socketid] === undefined){
the io.sockets.server.eio.clientsis an array containing a list of all the live socket id's. So use the code in the if statement to check if a particular socket ID is in this list.
这io.sockets.server.eio.clients是一个包含所有实时套接字 ID 列表的数组。因此,使用 if 语句中的代码来检查特定的套接字 ID 是否在此列表中。
回答by Insider
if (io.sockets.connected[socketID]) {
// do what you want
}
回答by pkarc
Socket.io >= 1.0, as Riwels answer, first you should check if the socket exists
Socket.io >= 1.0,正如 Riwels 回答的那样,首先你应该检查套接字是否存在
if(io.sockets.connected[a_socket_id]!=undefined){
console.log(io.sockets.connected[a_socket_id].connected); //or disconected property
}else{
console.log("Socket not connected");
}
回答by notgiorgi
In the newer versions, you can check socket.connectedproperty.
在较新的版本中,您可以检查socket.connected属性。
var socket = io(myEndpoint)
console.log(socket.connected) // logs true or false
Also you can set timeout
你也可以设置超时
setTimeout(function() {
if(! socket.connected) {
throw new Error('some error')
}
}, 5000)
This checks if socket connected in 5 seconds.
这会检查套接字是否在 5 秒内连接。

