How to catch a network connection error

I open the Qt / C ++ client url like

m_webSocket = new QWebSocket();
m_webSocket->open("wss://192.123.1.44:8087");

I want to catch any errors in the connection. How can I do it? I connected to the signal QWebSocket:error(QAbstractSocket::SocketError error), but never started it, even if my server is down.

Edit : I connect to the error signal as shown below,

m_webSocket = new QWebSocket();
connect(m_webSocket, SIGNAL(error(QAbstractSocket::SocketError error)), this, SLOT(onWebSocketError(QAbstractSocket::SocketError error)));
m_webSocket->open(url);

This does not seem to work.

+4
source share
1 answer

Connect a signal to QWebSocket error before opening the socket.

QWebSocket* pWebSocket = new QWebSocket;
connect(pWebSocket, &QWebSocket::error, [=](QAbstractSocket::SocketError error)
{
    // Handle error here...
    qDebug() << pWebSocket->errorString();
}

pWebSocket->open("wss://192.123.1.44:8087");

Note that this connection uses a lambda function that requires C ++ 11 . The connection to the slot will also work as usual.

++ 11 (Qt 5) : -

class MyClass : public QObject
{
   Q_OBJECT

   public:
       MyClass(QUrl url);

   protected slots:
       void Error(QAbstractSocket::SocketError error);

   private:
       QWebSocket* pWebSocket;
};


MyClass::MyClass(QUrl url)
{        
    QWebSocket* pWebSocket = new QWebSocket;
    connect(pWebSocket, &QWebSocket::error, pMyClass, &MyClass::Error);
    m_webSocket->open(url);
}

QObject:: connect QMetaObjectConnection, bool, , , , : -

// Old-style connection
if(!connect(m_webSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onWebSocketError(QAbstractSocket::SocketError))) )
{
    qDebug() << "Failed to connect to QWebSocket::error" <<  endl;
}

, , , - Qt connect.

. , . .

+5

Source: https://habr.com/ru/post/1610776/


All Articles