Socket.io:使用套接字ID检查连接的状态
我有一个连接的套接字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 }
有没有办法做到这一点?
对于高于1.0的版本,请检查Karan Kapoor的答案。 对于较老的版本,可以使用io.sockets.sockets[a_socket_id]
来访问任何连接的套接字,所以如果你已经设置了一个状态variables, 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"); }
截至今天,2015年2月,这里列出的方法都不适用于当前版本的Socket.io(1.1.0)。 所以在这个版本上,这是对我来说是如何工作的:
var socketList = io.sockets.server.eio.clients; if (socketList[user.socketid] === undefined){
io.sockets.server.eio.clients
是一个包含所有实时套接字标识列表的数组。 因此,使用if语句中的代码来检查一个特定的套接字ID是否在这个列表中。
if (io.sockets.connected[socketID]) { // do what you want }
Socket.io> = 1.0,Riwels回答,首先你应该检查socket是否存在
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"); }
在较新的版本中,您可以检查socket.connected
属性。
var socket = io(myEndpoint) console.log(socket.connected) // logs true or false
你也可以设置超时
setTimeout(function() { if(! socket.connected) { throw new Error('some error') } }, 5000)
这将检查是否在5秒钟内连接套接字。