c++qtqthreadsigintqtwebsockets

Terminating QWebSocketServer with connected sockets


I debug console multithreaded application written in C++/Qt 5.12.1. It is running on Linux Mint 18.3 x64.

This app has SIGINT handler, QWebSocketServer and QWebSocket table. It uses close() QWebSocketServer and call abort()/deleteLater() for items in QWebSocket table to handle the termination.

If the websocket client connects to this console app, then termination fails because of some running thread (I suppose it's internal QWebSocket thread). Termination is successful if there were no connections.

How to fix it? So that the app gracefully exits.


Solution

  • To gracefully quit the socket server we can attempt:

    The most important part is to allow the main thread event loop to run and wait on QWebSocketServer::closed() so that the slot calls QCoreApplication::quit().

    That can be done even with:

    connect(webSocketServer, &QWebSocketServer::closed,
            QCoreApplication::instance(), &QCoreApplication::quit);
    

    If we don't need more detailed reaction.

    After connecting that signal before all, proceed with pauseAccepting() to prevent more connections. Call QWebSocketServer::close.

    The below may not be needed if the above sufficient. You need to try the above first, and only if still have problems then deal with existing and pending connections. From my experience the behavior was varying on platforms and with some unique websocket implementations in the server environment (which is likely just Qt for you).

    As long as we have some array with QWebSocket instances, we can try to call QWebSocket::abort() on all of them to immediately release. This step seem to be described by the question author.

    Try to iterate pending connections with QWebSocketServer::nextPendingConnection() and call abort() for them. Call deleteLater, if that works as well.