Qt学习

Qt集成websocket客户端

2020-03-26  本文已影响0人  峰眼看世界
图片源自Qt官网

最近想做一个聊天软件,Qt内置websocket模块,本文就简单演示下Qt下集成websocket客户端。至于为什么不用socket,因为还想有web端的聊天室,web端支持全双工通信的自然会选用websocket协议。

1. 项目配置

需要在.pro项目文件中添加websockets模块:

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!!!";
}

4. 总结

上一篇 下一篇

猜你喜欢

热点阅读