gaj
gaj

Reputation: 327

How to catch websocket connection error

I'm opening a url from Qt/c++ client like,

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

I want catch any errors in connection. How do I do that? I've connected to signal QWebSocket:error(QAbstractSocket::SocketError error), but I never get it triggered even if my server is not running.

Edit: I'm connecting to error signal as below,

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

This seems to be not working.

Upvotes: 9

Views: 8211

Answers (2)

scopchanov
scopchanov

Reputation: 8399

As described in the documentation:

Note: Signal error is overloaded in this class. To connect to this signal by using the function pointer syntax, Qt provides a convenient helper for obtaining the function pointer as shown in this example:

connect(webSocket, QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error),
[=](QAbstractSocket::SocketError error){ /* ... */ });

Of course, instead of lambda function, you could connect to a normal one, but the QOverload part is important.

Upvotes: 9

TheDarkKnight
TheDarkKnight

Reputation: 27611

Connect to the QWebSocket error signal, 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, which requires C++ 11. Connection to a slot in the usual manner will also work.

Without C++ 11, use a standard (Qt 5) connection: -

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);
}

As QObject::connect returns a QMetaObjectConnection, which contains an overloaded bool operator, you can check the return from the call to connect, to ensure that a valid signal and slot was found, and valid arguments provided: -

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

However, this is largely redundant, as a failed connection usually produces debug output informing you of this issue, from within Qt's connect call.

NOTE, in the old-style connection syntax, the argument list does not name the arguments, only the type is provided. Adding a name will produce a failed connection.

Upvotes: 5

Related Questions