使用QT中 QTcpSocket来检测设备的网络状态:

函数返回true,设备网络状态正常,返回false,设备网络异常。

boolTcpIpSocket::sendATcpSocketToIp(QStringip){m_ipAdress=ip;abort();connectToHost(m_ipAdress,port);//等待timeout时间,如果仍然不通,则异常returnwaitForConnected(timeout);}

要实现实时一直检测,使用while:

runWhile=true;runBreak=false;boolretPing;while(runWhile){retPing=m_senderAgent.sendATcpSocketToIp(ipAdress);if(retPing==true){//ping成功,目标ip网络正常,发送commandSuccessedemitcommandSuccessed();}else{//ping失败,目标ip网络不正常,发送commandFailedemitcommandFailed();}sleep(1000);//sleep1sif(runBreak){break;}}//endofwhile

运行中还存在问题的是,假如使用另外一个函数,在某个时刻触发,使runBreak = true ,或者 runWhile = false,但是这个while仍然一直循环执行,不会跳出,但是当注释掉sleep(1000)后,while就会跳出。但是注释掉sleep(1000)后,该while会占用大量cpu资源全力发送数据包(这个不是想要的,只能两害取其轻了)。