美文网首页QT GUI编程
QT Websocket实现服务器客户端通信(客户端部分)

QT Websocket实现服务器客户端通信(客户端部分)

作者: Zeal_7ede | 来源:发表于2018-06-01 11:51 被阅读0次

    一 界面


    客户端 服务端

    二 源码
    1.客户端部分
    Clientdialog.cc

    #include <QLabel>
    #include <QWidget>
    #include <QHBoxLayout>
    #include <QVBoxLayout>
    #include <QtCore>
    #include <QDebug>
    #include <iostream>
    
    ClientDialog::ClientDialog(const QUrl &url,bool debug,QWidget *parent)
        : QWidget(parent),m_url(url),m_debug(debug)
    {
        //layout1
        QLabel *iplabel = new QLabel("IP地址");
        m_iplineedit =new QLineEdit;
        QLabel *portlabel =new QLabel("端口");
        m_portspinbox = new QSpinBox;
        m_portspinbox->setRange(0,65535);
        m_linkbutton = new QPushButton("连接");
        m_disconnectbutton = new QPushButton("断开");
        pButtonGroup = new QButtonGroup();
        pButtonGroup->setExclusive(true);
        m_linkbutton->setCheckable(true);
        m_disconnectbutton->setCheckable(true);
        pButtonGroup->addButton(m_linkbutton,0);
        pButtonGroup->addButton(m_disconnectbutton,1);
    
        QHBoxLayout *qhboxlayout1 = new QHBoxLayout;
        qhboxlayout1->addWidget(iplabel);
        qhboxlayout1->addWidget(m_iplineedit);
        qhboxlayout1->addWidget(portlabel);
        qhboxlayout1->addWidget(m_portspinbox);
        qhboxlayout1->addWidget(m_linkbutton);
        qhboxlayout1->addWidget(m_disconnectbutton);
    
        //layout2
        QLabel *sendmessagelabel = new QLabel("发送消息");
        QHBoxLayout *qhboxlayout2 = new QHBoxLayout;
        qhboxlayout2->addWidget(sendmessagelabel);
    
        //layout3
        m_sendmessagetextedit = new QTextEdit;
        m_sendmessagetextedit->setFixedHeight(50);
        m_sendbutton = new QPushButton("发送");
        m_sendbutton->setFixedHeight(50);
        QHBoxLayout *qhboxlayout3 = new QHBoxLayout;
        qhboxlayout3->addWidget(m_sendmessagetextedit);
        qhboxlayout3->addWidget(m_sendbutton);
    
        //layout4
        QLabel *receivemessagelabel = new QLabel("接收消息");
        QHBoxLayout *qhboxlayout4 = new QHBoxLayout;
        qhboxlayout4->addWidget(receivemessagelabel);
    
        //layout5
        m_receivemessageTextEdit = new QTextEdit;
        QHBoxLayout *qhboxlayout5 = new QHBoxLayout;
        qhboxlayout5->addWidget(m_receivemessageTextEdit);
        m_receivemessageTextEdit->setReadOnly(true);
    
        //layout6
        statusLabel = new QLabel("连接状态");
        m_clean = new QPushButton("清除");
        QHBoxLayout *qhboxlayout6 = new QHBoxLayout;
        qhboxlayout6->addWidget(statusLabel);
        qhboxlayout6->addStretch();
        qhboxlayout6->addWidget(m_clean);
        //
        QVBoxLayout *mainlayout = new QVBoxLayout;
        mainlayout->addLayout(qhboxlayout1,1);
        mainlayout->addLayout(qhboxlayout2,0.5);
        mainlayout->addLayout(qhboxlayout3,1);
        mainlayout->addLayout(qhboxlayout4,0.5);
        mainlayout->addLayout(qhboxlayout5,3);
        mainlayout->addLayout(qhboxlayout6,1);
        setLayout(mainlayout);
        setWindowTitle("Websocket Client");
    
        connect(m_linkbutton,SIGNAL(clicked(bool)),this,SLOT(connectToServer()));
        connect(m_disconnectbutton,SIGNAL(clicked(bool)),this,SLOT(stopClicked()));
        connect(m_sendbutton,SIGNAL(clicked(bool)),this,SLOT(onSendButtonClicked()));
        connect(m_clean,SIGNAL(clicked(bool)),this,SLOT(onCleanButtonClicked()));
        connect(&m_websocket,SIGNAL(connected()),this,SLOT(onconnected()));
        connect(&m_websocket,SIGNAL(disconnected()),this,SLOT(closeConnection()));
        connect(&m_websocket,SIGNAL(textMessageReceived(QString)),this,SLOT(onTextMessageReceived(QString)));
    }
    
    ClientDialog::~ClientDialog()
    {
        m_websocket.errorString();
        m_websocket.close();
    }
    //断开连接操作
    void ClientDialog::closeConnection(){
        m_linkbutton->setEnabled(true);
        m_disconnectbutton->setEnabled(false);
        m_sendmessagetextedit->setEnabled(false);
        m_sendbutton->setEnabled(false);
        m_receivemessageTextEdit->setEnabled(false);
        m_clean->setEnabled(false);
        statusLabel->setText(tr("disconnected"));
    }
    //连接服务器
    void ClientDialog::connectToServer()
    {
        QString path = QString("ws://%1:%2").arg(m_iplineedit->text()).arg(m_portspinbox->text());
        QUrl url = QUrl(path);
        m_websocket.open(url);
    }
    //连接上之后
    void ClientDialog::onconnected(){
        qDebug() << "hello word!";
        statusLabel->setText(tr("connected"));
        m_linkbutton->setEnabled(false);
        m_disconnectbutton->setEnabled(true);
        m_sendmessagetextedit->setEnabled(true);
        m_sendbutton->setEnabled(true);
        m_receivemessageTextEdit->setEnabled(true);
        m_clean->setEnabled(true);
    }
    //收到消息
    void ClientDialog::onTextMessageReceived(const QString &message)
    {
        QString time = current_date_time->currentDateTime().toString("yyyy.MM.dd hh:mm:ss.zzz ddd");
        m_receivemessageTextEdit->setText(time + "\n" + message);
    }
    //断开
    void ClientDialog::stopClicked()
    {
        m_websocket.close();
    }
    //发送消息
    void ClientDialog::onSendButtonClicked()
    {
        QString msg= m_sendmessagetextedit->document()->toPlainText();
        m_websocket.sendTextMessage(msg);
    }
    //清除内容
    void ClientDialog::onCleanButtonClicked()
    {
        m_receivemessageTextEdit->clear();
    }
    

    main.cc

    #include "Clientdialog.hpp"
    #include <QApplication>
    #include <QDir>
    #include <QTextCodec>
    #include <QCoreApplication>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        QDir::setCurrent(QApplication::applicationDirPath());
        QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));//set QString codec
        QUrl url;
        ClientDialog w(url);
        w.show();
        return a.exec();
    }
    

    Clientdialog.hpp

    #ifndef CLIENTDIALOG_HPP
    #define CLIENTDIALOG_HPP
    #include <QDialog>
    #include <QLineEdit>
    #include <QLabel>
    #include <QTextEdit>
    #include <QListWidget>
    #include <QPushButton>
    #include <QSpinBox>
    #include <QButtonGroup>
    #include <QObject>
    #include <QWidget>
    #include <QUrl>
    #include "qwebsocket.hpp"
    #include <time.h>
    #include <QByteArray>
    
    class ClientDialog : public QWidget
    {
        Q_OBJECT
    
    public:
        explicit ClientDialog(const QUrl &url,bool debug = false, QWidget *parent=0);
        ~ClientDialog();
    
    Q_SIGNALS:
    void closed();
    
    private Q_SLOTS:
     void connectToServer();
     void onTextMessageReceived(const QString &message);
     void closeConnection();
    
    public slots:
        void stopClicked();
        void onconnected();
        void onSendButtonClicked();
        void onCleanButtonClicked();
    
    private:
         QLineEdit *m_iplineedit;
         QSpinBox *m_portspinbox;
         QPushButton *m_linkbutton;
         QPushButton *m_disconnectbutton;
         QTextEdit *m_sendmessagetextedit;
         QPushButton *m_sendbutton;
         QTextEdit *m_receivemessageTextEdit;
         QPushButton *m_clean;
         QLabel *statusLabel;
         QButtonGroup *pButtonGroup;
         QUrl m_url;
         QWebSocket m_websocket;
         bool m_debug;
         QDateTime *current_date_time;
    };
    #endif // CLIENTDIALOG_HPP
    

    由于本人用的是QT4.5.0版本没有QWebsocket类,所以所需类是自己下载添加的,需要在
    pro文件里添加源文件路径。本人
    Client.pro

    #-------------------------------------------------
    #
    # Project created by QtCreator 2018-05-10T16:24:00
    #
    #-------------------------------------------------
    
    QT       += core gui network
    
    greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
    
    TARGET = Client
    TEMPLATE = app
    
    # The following define makes your compiler emit warnings if you use
    # any feature of Qt which has been marked as deprecated (the exact warnings
    # depend on your compiler). Please consult the documentation of the
    # deprecated API in order to know how to port your code away from it.
    DEFINES += QT_DEPRECATED_WARNINGS QT_VERSION_LESS_FIVE
    
    INCLUDEPATH += $$PWD/../QtWebsocket
    
    # You can also make your code fail to compile if you use deprecated APIs.
    # In order to do so, uncomment the following line.
    # You can also select to disable deprecated APIs only up to a certain version of Qt.
    #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0
    
    
    SOURCES += \
            main.cc \
            Clientdialog.cc
    
    HEADERS += \
            Clientdialog.hpp
    
    
    DESTDIR = $$PWD/../Bin
    
    LIBS +=-L$$DESTDIR -lQtWebsocket
    

    各文件及目录如下:


    源文件目录
    程序及库目录
    QWebsocket类文件目录

    相关文章

      网友评论

        本文标题:QT Websocket实现服务器客户端通信(客户端部分)

        本文链接:https://www.haomeiwen.com/subject/ttvhsftx.html