1 引入websocket
QT += core gui websockets
2. 编写dialog.h头文件
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QWebSocket>
QT_BEGIN_NAMESPACE
namespace Ui { class Dialog; }
QT_END_NAMESPACE
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = nullptr);
~Dialog();
public slots:
void createDataRecvWS(); /*-<创建websocket连接 */
private:
Ui::Dialog *ui;
QWebSocket *dataRecvWS; /*-<websocket类 */
private slots:
void onConnected(); /*-<socket建立成功后,触发该函数 */
void onTextReceived(QString msg); /*-<收到Sev端的数据时,触发该函数 */
void onDisConnected(); /*-<socket连接断开后,触发该函数 */
};
#endif // DIALOG_H
3. 编写dialog.cpp源文件
#include "dialog.h"
#include "ui_dialog.h"
#include <QDebug>
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Dialog)
{
ui->setupUi(this);
dataRecvWS = Q_NULLPTR;
}
Dialog::~Dialog()
{
delete ui;
}
/**
* @brief 创建websocket链接
*/
void Dialog::createDataRecvWS() {
if (dataRecvWS == Q_NULLPTR) {
dataRecvWS = new QWebSocket();
qDebug()<<"create websocket!";
connect(dataRecvWS,&QWebSocket::disconnected,this,&Dialog::onDisConnected);
connect(dataRecvWS,&QWebSocket::textMessageReceived,this,&Dialog::onTextReceived);
connect(dataRecvWS,&QWebSocket::connected,this,&Dialog::onConnected);
dataRecvWS->open(QUrl("ws://127.0.0.1:9000/ws"));
}
}
/**
* @breaf 判断连接状态
* @note 当连接成功后,触发该函数
*/
void Dialog::onConnected(){
qDebug() << "DataReveive websocket is already connect!";
qDebug() << "Address:" << dataRecvWS->peerAddress();
dataRecvWS->sendTextMessage("Hello, server!!");
}
/**
* @breaf 数据处理函数
* @param msg, 数据信息
* @note 当收到服务端发送的数据时,触发该函数
*/
void Dialog::onTextReceived(QString msg){
qDebug()<<"----------------data-----------------";
qDebug()<<msg;
}
/**
* @breaf 连接断开
* @note 当连接断开时,触发该函数
*/
void Dialog::onDisConnected(){
qDebug()<<"Dialog websocket is disconnected!!!";
}
QML中的websockets
import QtQuick 2.0
import Qt.WebSockets 1.0
Text {
width: 480
height: 48
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
WebSocket {
id: socket
url: "ws://echo.websocket.org"
active: true
onTextMessageReceived: {
text = message
}
onStatusChanged: {
if (socket.status == WebSocket.Error) {
console.log("Error: " + socket.errorString)
} else if (socket.status == WebSocket.Open) {
socket.sendTextMessage("ping")
} else if (socket.status == WebSocket.Closed) {
text += "\nSocket closed"
}
}
}
}