qtwebsocketqt5qtwebsockets

QWebSocket from QTcpSocket


I've written a small web server using QTcpServer, etc... It works fine so I wanted to get a bit further and implement Qt's WebSocket functionality. I want the WebSocket-Server to be reachable on the same port as my web server (due to limitations at my clients network).

My WebSocket-Server should be accessible at /admin/socket so I need a way to 'upgrade' a QTcpSocket (accessible from the request handler for /admin/socket) to a QWebSocket. QWebSocket has this functionality in this constructor which is used by this upgrade method in QWebSocketServerPrivate but it is all private and only used internally by the QWebSocketServer.

Is there a way to achieve what I described above? Do I have to implement my own WebSocket handler?


Solution

  • You need to copy the requisite files from Qt's sources into your project, wrap the QWebSocket into a namespace so it won't clash with Qt's own, and make the constructor non-private. That's the only way to achieve that without writing a lot of your own code, and without invoking undefined behavior.

    To use your type, make it visible via using; it will hide the Qt's ::QObject then:

    #include <QtCore>
    
    namespace Foo { class QObject {}; }
    
    int main() {
       using Foo::QObject;
    
       //         ours vvvvvvv        Qt's vvvvvvv
       Q_ASSERT(sizeof(QObject) < sizeof(::QObject));
    }
    

    Qt comes with a source code for a reason: you're supposed to use it when it makes sense!