QT Websocket實(shí)現(xiàn)服務(wù)器客戶端通信(客戶端部分)

一 界面


客戶端
服務(wù)端

二 源碼
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("發(fā)送消息");
    QHBoxLayout *qhboxlayout2 = new QHBoxLayout;
    qhboxlayout2->addWidget(sendmessagelabel);

    //layout3
    m_sendmessagetextedit = new QTextEdit;
    m_sendmessagetextedit->setFixedHeight(50);
    m_sendbutton = new QPushButton("發(fā)送");
    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("連接狀態(tài)");
    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"));
}
//連接服務(wù)器
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();
}
//發(fā)送消息
void ClientDialog::onSendButtonClicked()
{
    QString msg= m_sendmessagetextedit->document()->toPlainText();
    m_websocket.sendTextMessage(msg);
}
//清除內(nèi)容
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類文件目錄
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末撑毛,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子盟榴,更是在濱河造成了極大的恐慌届囚,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,378評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件赁炎,死亡現(xiàn)場離奇詭異醉箕,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)徙垫,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,356評論 2 382
  • 文/潘曉璐 我一進(jìn)店門讥裤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人姻报,你說我怎么就攤上這事己英。” “怎么了逗抑?”我有些...
    開封第一講書人閱讀 152,702評論 0 342
  • 文/不壞的土叔 我叫張陵剧辐,是天一觀的道長。 經(jīng)常有香客問我邮府,道長荧关,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,259評論 1 279
  • 正文 為了忘掉前任褂傀,我火速辦了婚禮忍啤,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己同波,他們只是感情好鳄梅,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,263評論 5 371
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著未檩,像睡著了一般戴尸。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上冤狡,一...
    開封第一講書人閱讀 49,036評論 1 285
  • 那天孙蒙,我揣著相機(jī)與錄音,去河邊找鬼悲雳。 笑死挎峦,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的合瓢。 我是一名探鬼主播坦胶,決...
    沈念sama閱讀 38,349評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼晴楔!你這毒婦竟也來了顿苇?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 36,979評論 0 259
  • 序言:老撾萬榮一對情侶失蹤滥崩,失蹤者是張志新(化名)和其女友劉穎岖圈,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體钙皮,經(jīng)...
    沈念sama閱讀 43,469評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,938評論 2 323
  • 正文 我和宋清朗相戀三年顽决,在試婚紗的時候發(fā)現(xiàn)自己被綠了短条。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,059評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡才菠,死狀恐怖茸时,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情赋访,我是刑警寧澤可都,帶...
    沈念sama閱讀 33,703評論 4 323
  • 正文 年R本政府宣布,位于F島的核電站蚓耽,受9級特大地震影響渠牲,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜步悠,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,257評論 3 307
  • 文/蒙蒙 一签杈、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧鼎兽,春花似錦答姥、人聲如沸铣除。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,262評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽尚粘。三九已至,卻和暖如春敲长,著一層夾襖步出監(jiān)牢的瞬間郎嫁,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工潘明, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留行剂,地道東北人。 一個月前我還...
    沈念sama閱讀 45,501評論 2 354
  • 正文 我出身青樓钳降,卻偏偏與公主長得像厚宰,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子遂填,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,792評論 2 345

推薦閱讀更多精彩內(nèi)容