Simple connection of QT websocket


Websocket preparation

There are two types of sockets on QT, tcpsocket and websocket. This time, only websocket is involved.

Websocket docking

1. First, you need to import it into the. Pro file

QT += websockets

And include header files

#include <QWebSocket>

2. Initialize websocket

QWebSocket  *websocket;
private slots:
    Void ondisconnected(); // execute method after disconnection
    Void onconnected(); // execute the method after the connection succeeds
    Void onbinarymessagereceived (qbytearray message); // execute the method after receiving data (here is the method for receiving binary data)
    Void ontextmessagereceived (qstring message) // execute the method after receiving data (here is the method of receiving character data)
    Void reconnect(); // execute method when reconnection is required

In the above methods, please select the method of receiving data according to the type of data sent in the background, otherwise the data may not be received, the performance data in QT is empty, and the packet capturing software displays the data.

3. Docking corresponding signal slots and methods

websocket = new QWebSocket();
connect(websocket, SIGNAL(binaryMessageReceived(QByteArray)), this, SLOT(onBinaryMessageReceived(QByteArray)),Qt::UniqueConnection);


void Form::onDisconnected()
    qDebug()<<"websocket is disconnected";
void Form::onConnected()
    qDebug()<<"connect successful";
    QString message =  "";

void Form::onBinaryMessageReceived(QByteArray message)
void WalletForm::reconnect()
   qDebug()<<"websocket reconnected";