qt 网络状态检测
qt網絡狀態檢測使用popen來實現,當然你也可以使用QProcess的start(“cmd /c ping www.baidu.com”)來實現。
本文通過一個在線程中使用QTimer定時器來實現每間隔幾秒ping一次網絡,實際使用時,一般在post或者get接口訪問失敗后打開網絡監控,網絡連上后,關掉定時器來減小開銷。
由于cmd /c部分情況下會出現控制臺窗口。所以windows下可以使用:
AllocConsole(); //為調用進程分配一個新的控制臺
ShowWindow(GetConsoleWindow(), SW_HIDE); //隱藏自己創建的控制臺
實例如下:
.h
.cpp
NetworkCheck::NetworkCheck(QObject *parent) {AllocConsole(); //為調用進程分配一個新的控制臺ShowWindow(GetConsoleWindow(), SW_HIDE); //隱藏自己創建的控制臺m_thread = new QThread;connect(m_thread,SIGNAL(started()),this,SLOT(slotStart()));m_timer = new QTimer;connect(m_timer,SIGNAL(timeout()),this,SLOT(TimeOut()));m_timer->moveToThread(m_thread);this->moveToThread(m_thread); }NetworkCheck* NetworkCheck::instance() {static NetworkCheck pInstance;return &pInstance; }void NetworkCheck::slotStart() {QString url = "cmd /c ping www.baidu.com";QString res = getCmdResult(url);qDebug()<<__FUNCTION__<<__LINE__<<res;if (res.contains("找不到主機")){if (!m_timer->isActive())m_timer->start(5000);m_status = false;}else{m_timer->stop();if (!m_status)//網絡重連成功{m_status = true;emit signalReNetwork();}} }/// 執行cmd指令并返回結果 QString NetworkCheck::getCmdResult(const QString &strCmd) {char buf[10240] = {0};FILE *pf = NULL;if( (pf = _popen(strCmd.toStdString().c_str(), "r")) == NULL ){return "";}std::string strResult;while(fgets(buf, sizeof buf, pf)){strResult += buf;}_pclose(pf);unsigned int iSize = strResult.size();if(iSize > 0 && strResult[iSize - 1] == '\n') // linux{strResult = strResult.substr(0, iSize - 1);}return QString::fromLocal8Bit(strResult.c_str()); }void NetworkCheck::checkNetwork() {m_thread->start(); }void NetworkCheck::TimeOut() {slotStart(); }總結
- 上一篇: Qt实现文字滚动、翻动动画
- 下一篇: 《高效能程序员修炼》读书笔记