Important: Please read the Qt Code of Conduct -

How to check if websocket is still connected?

  • Hi,

    I am trying to know, if websocket is still connected to server. I use timer to ping server:

    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this{;

    On wesocket error I try to reconnect, but it doesn't get called, unless I restart client:

    connect(&m_webSocket, static_cast<void(QWebSocket::*)(QAbstractSocket::SocketError)>(&QWebSocket::error),
    [=](QAbstractSocket::SocketError error){
    qDebug() << m_webSocket.errorString();
    QTimer::singleShot(4000, this, [=]{

    The problem is that even if I turn off server network, ping request still is send and I do not receive any error, like socket is still open, but it isn't. If I restart client, it then tries to connect and if it fails it waits for 4 seconds and retries like it should. I am using QT 5.10. Why do I not receive any error nor any stateChanged callback when server is suddenly unreachable and socket isn't closed gracefully?

  • When you emit a ping you should listen for the pong() ( if you don't receive it within, say 4seconds, then do your thing.

    Be aware that pinging too often might lead the server to cut you off

  • Thank you for responding, I will do just that.

Log in to reply