Simple connection of QT websocket

Time:2019-11-21

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
Signal:

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

Method:

void Form::onDisconnected()
{
    qDebug()<<"websocket is disconnected";
    reconnect();
}
void Form::onConnected()
{
    qDebug()<<"connect successful";
    QString message =  "";
    websocket->sendTextMessage(message);

}
void Form::onBinaryMessageReceived(QByteArray message)
{
}
void WalletForm::reconnect()
{
   qDebug()<<"websocket reconnected";
   websocket->abort();
   websocket->open((QUrl(url)));
}

Recommended Today

Using native es module in node.js

Original: using ES modules natively in node.js By Axel rauschmayer Starting from version 8.5.0, node.js supports native es modules, which can be turned on through command-line options. Much of the new functionality is due to Bradley Farias. 1. demo The code directory structure of this example is as follows: esm-demo/ lib.mjs main.mjs lib.mjs: export function […]