From c460505d2e120542c1f667e58d9a9e52f0f2700e Mon Sep 17 00:00:00 2001 From: Klaus Basan Date: Sat, 18 Feb 2017 05:06:00 +0100 Subject: [PATCH] refs #883, refs #869 using ping as socket is slow/sometimes has trouble --- src/blackmisc/network/networkutils.cpp | 32 ++++++++++++++++++-------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/src/blackmisc/network/networkutils.cpp b/src/blackmisc/network/networkutils.cpp index bb27ab90a..da97be709 100644 --- a/src/blackmisc/network/networkutils.cpp +++ b/src/blackmisc/network/networkutils.cpp @@ -32,6 +32,7 @@ #include #include #include +#include #include using namespace BlackConfig; @@ -118,20 +119,31 @@ namespace BlackMisc return false; } + // KB: I have had an issue with QTcpSocket. It was stuck in HostLookupState and did + // only recover after a reboot for no obvious reason. + // Currently trying the ping alternative + bool ping = CNetworkUtils::canPing(hostAddress); + if (ping) { return true; } + // http://qt-project.org/forums/viewthread/9346 + // socket.waitForConnected() unrelaiable under Windows, see Qt docu QTcpSocket socket; - bool connected = false; - socket.connectToHost(hostAddress, static_cast(port)); - if (!socket.waitForConnected(timeoutMs)) + QTcpSocket::SocketState socketState; + socket.connectToHost(hostAddress, static_cast(port), QTcpSocket::ReadOnly); + socketState = socket.state(); + bool connected = (socketState == QTcpSocket::ConnectedState); + if (!connected) { - message = QObject::tr("Connection failed : %1", "BlackMisc").arg(socket.errorString()); - connected = false; - } - else - { - message = QObject::tr("OK, connected", "BlackMisc"); - connected = true; + QEventLoop eventLoop; + QObject::connect(&socket, &QTcpSocket::connected, &eventLoop, &QEventLoop::quit); + QTimer::singleShot(timeoutMs, &eventLoop, &QEventLoop::quit); + eventLoop.exec(); } + socketState = socket.state(); + connected = (socketState == QTcpSocket::ConnectedState); + message = connected ? + QObject::tr("OK, connected", "BlackMisc") : + QObject::tr("Connection failed : '%1'", "BlackMisc").arg(socket.errorString()); socket.close(); return connected; }