我有一个连接的套接字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
}
有没有办法这样做?
我有一个连接的套接字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]
访问任何连接的套接字,因此如果您已在其上设置了状态变量,则 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
是包含所有活动socket ID的列表数组。因此,使用if语句中的代码来检查特定的socket ID是否在此列表中。
if (io.sockets.connected[socketID]) {
// do what you want
}
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");
}
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秒内连接成功。
io.sockets.clients()
获取客户端。然后我遍历数组,搜索正确的套接字(比较套接字对象上的ID,.id
属性)。当我找到它时,我检查了disconnected
属性。为了更准确地检查客户端是否存活,我编写了一个简单的保持活动系统。 - franzlorenzon