使用QT中 QTcpSocket来检测设备的网络状态:
函数返回true,设备网络状态正常,返回false,设备网络异常。
bool TcpIpSocket::sendATcpSocketToIp(QString ip){
m_ipAdress = ip;
abort();
connectToHost(m_ipAdress, port);
//等待timeout时间,如果仍然不通,则异常
return waitForConnected(timeout);
}
要实现实时一直检测,使用while:
runWhile = true; runBreak = false;
bool retPing;
while(runWhile){
retPing = m_senderAgent.sendATcpSocketToIp(ipAdress);
if(retPing == true){
//ping 成功,目标ip网络正常,发送commandSuccessed
emit commandSuccessed();
}else{
//ping 失败,目标ip网络不正常,发送commandFailed
emit commandFailed();
}
sleep(1000); // sleep 1s
if(runBreak){
break;
}
}//end of while
运行中还存在问题的是,假如使用另外一个函数,在某个时刻触发,使runBreak = true ,或者 runWhile = false,但是这个while仍然一直循环执行,不会跳出,但是当注释掉sleep(1000)后,while就会跳出。但是注释掉sleep(1000)后,该while会占用大量cpu资源全力发送数据包(这个不是想要的,只能两害取其轻了)。
转载于:https://blog.51cto.com/xuedengfeng/1870947