Qt-Qt使用QWebsocket实现服务端和客户端通信
相关资料:
https://blog.csdn.net/qq_40110291/article/details/103734258 Qt websocket 服务端和客户端通信
实例代码(服务端):
.pro
1 QT += core gui 2 QT += websockets 3 4 greaterThan(QT_MAJOR_VERSION, 4): QT += widgets 5 6 CONFIG += c++11 7 8 # The following define makes your compiler emit warnings if you use 9 # any Qt feature that has been marked deprecated (the exact warnings 10 # depend on your compiler). Please consult the documentation of the 11 # deprecated API in order to know how to port your code away from it. 12 DEFINES += QT_DEPRECATED_WARNINGS 13 14 # You can also make your code fail to compile if it uses deprecated APIs. 15 # In order to do so, uncomment the following line. 16 # You can also select to disable deprecated APIs only up to a certain version of Qt. 17 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 18 19 SOURCES += \ 20 main.cpp \ 21 mainwindow.cpp 22 23 HEADERS += \ 24 mainwindow.h 25 26 FORMS += \ 27 mainwindow.ui 28 29 # Default rules for deployment. 30 qnx: target.path = /tmp/$${TARGET}/bin 31 else: unix:!android: target.path = /opt/$${TARGET}/bin 32 !isEmpty(target.path): INSTALLS += target
main.cpp
1 #include "mainwindow.h" 2 3 #include4 5 int main(int argc, char *argv[]) 6 { 7 QApplication a(argc, argv); 8 MainWindow w; 9 w.show(); 10 return a.exec(); 11 }
mainwindow.h
1 #ifndef MAINWINDOW_H 2 #define MAINWINDOW_H 3 4 #include5 6 #include 7 #include 8 9 QT_BEGIN_NAMESPACE 10 namespace Ui { class MainWindow; } 11 QT_END_NAMESPACE 12 13 class MainWindow : public QMainWindow 14 { 15 Q_OBJECT 16 17 public: 18 MainWindow(QWidget *parent = nullptr); 19 ~MainWindow(); 20 21 public slots: 22 void onStartButtonClick(); 23 void onStopButtonClick(); 24 void onSendButtonClick(); 25 void onCleanButtonClick(); 26 27 Q_SIGNALS: 28 void closed(); 29 private Q_SLOTS: 30 void onNewConnection(); 31 void processTextMessage(QString message); 32 void socketDisconnected(); 33 34 private: 35 Ui::MainWindow *ui; 36 37 QWebSocketServer *m_WebSocketServer; 38 QList m_clients; 39 bool m_debug; 40 QWebSocket *pSocket; 41 QDateTime *current_date_time; 42 43 }; 44 #endif // MAINWINDOW_H
mainwindow.cpp
1 #include "mainwindow.h" 2 #include "ui_mainwindow.h" 3 4 MainWindow::MainWindow(QWidget *parent) 5 : QMainWindow(parent) 6 , ui(new Ui::MainWindow) 7 { 8 ui->setupUi(this); 9 10 m_WebSocketServer = new QWebSocketServer("server", QWebSocketServer::NonSecureMode); 11 connect(m_WebSocketServer, SIGNAL(newConnection()), this, SLOT(onNewConnection())); 12 connect(ui->startButton, SIGNAL(clicked(bool)), this, SLOT(onStartButtonClick())); 13 connect(ui->stopButton, SIGNAL(clicked(bool)), this, SLOT(onStopButtonClick())); 14 connect(ui->cleanButton, SIGNAL(clicked(bool)), this, SLOT(onCleanButtonClick())); 15 connect(ui->sendButton, SIGNAL(clicked(bool)), this, SLOT(onSendButtonClick())); 16 17 } 18 19 MainWindow::~MainWindow() 20 { 21 delete ui; 22 } 23 24 void MainWindow::onStartButtonClick() 25 { 26 int i_port = ui->monitorSpinBox->text().toInt(); 27 m_WebSocketServer->listen(QHostAddress::Any, i_port); 28 ui->startButton->setEnabled(false); 29 ui->stopButton->setEnabled(true); 30 } 31 32 void MainWindow::onStopButtonClick() 33 { 34 ui->startButton->setEnabled(true); 35 ui->stopButton->setEnabled(false); 36 m_WebSocketServer->close(); 37 } 38 39 void MainWindow::onSendButtonClick() 40 { 41 QString msg = ui->sendTextedit->document()->toPlainText(); 42 for (int i=0;i) 43 { 44 m_clients.at(i)->sendTextMessage(msg); 45 } 46 } 47 48 void MainWindow::onCleanButtonClick() 49 { 50 ui->receiveTextEdit->clear(); 51 } 52 53 void MainWindow::onNewConnection() 54 { 55 ui->startButton->setEnabled(false); 56 ui->stopButton->setEnabled(true); 57 ui->sendTextedit->setEnabled(true); 58 ui->sendButton->setEnabled(true); 59 ui->cleanButton->setEnabled(true); 60 61 pSocket = m_WebSocketServer->nextPendingConnection(); 62 63 connect(pSocket, SIGNAL(textMessageReceived(QString)), this, SLOT(processTextMessage(QString))); 64 connect(pSocket, SIGNAL(disconnected()), this, SLOT(socketDisconnected())); 65 66 QString item = pSocket->peerAddress().toString(); 67 ui->linkclientListWidget->addItem(item); 68 m_clients << pSocket; 69 } 70 71 void MainWindow::processTextMessage(QString message) 72 { 73 QString time = current_date_time->currentDateTime().toString("yyyy.MM.dd hh:mm:ss.zzz ddd"); 74 QString item = pSocket->peerAddress().toString(); 75 ui->receiveTextEdit->append(time + "" + item + "\n" + message); 76 } 77 78 void MainWindow::socketDisconnected() 79 { 80 ui->startButton->setEnabled(true); 81 ui->stopButton->setEnabled(false); 82 ui->sendButton->setEnabled(false); 83 ui->sendTextedit->setEnabled(false); 84 ui->receiveTextEdit->setEnabled(false); 85 ui->cleanButton->setEnabled(false); 86 }
mainwindow.ui
1 <?xml version="1.0" encoding="UTF-8"?> 2"4.0"> 3 <class>MainWindowclass> 4 class="QMainWindow" name="MainWindow"> 5 "geometry"> 6 137 120 80 9800 10600 11"windowTitle"> 14 <string>MainWindowstring> 15 16class="QWidget" name="centralwidget"> 17 152class="QLabel" name="label"> 18 30"geometry"> 19 2620 2530 2140 2254 2312 24"text"> 27 <string>TextLabelstring> 28 29class="QSpinBox" name="monitorSpinBox"> 31 43"geometry"> 32 3933 38100 3430 35101 3622 37"maximum"> 40 4250000 41class="QPushButton" name="startButton"> 44 56"geometry"> 45 5246 51220 4730 4880 4920 50"text"> 53 <string>启动string> 54 55class="QPushButton" name="stopButton"> 57 69"geometry"> 58 6559 64320 6030 6180 6220 63"text"> 66 <string>停止string> 67 68class="QTextEdit" name="sendTextedit"> 70 79"geometry"> 71 7872 7730 7380 74361 7570 76class="QPushButton" name="sendButton"> 80 92"geometry"> 81 8882 87410 8380 8480 8520 86"text"> 89 <string>发送string> 90 91class="QTextEdit" name="receiveTextEdit"> 93 102"geometry"> 94 10195 10030 96220 97351 98211 99class="QLabel" name="label_2"> 103 115"geometry"> 104 111105 11030 106200 10754 10812 109"text"> 112 <string>TextLabelstring> 113 114class="QLabel" name="label_3"> 116 128"geometry"> 117 124118 123390 119200 12054 12112 122"text"> 125 <string>TextLabelstring> 126 127class="QPushButton" name="cleanButton"> 129 141"geometry"> 130 137131 136630 132190 13380 13420 135"text"> 138 <string>清除string> 139 140class="QListWidget" name="linkclientListWidget"> 142 151"geometry"> 143 150144 149410 145230 146256 147192 148class="QMenuBar" name="menubar"> 153 162"geometry"> 154 161155 1600 1560 157800 15822 159class="QStatusBar" name="statusbar"/> 163 164165 166
客户端:
.pro
1 QT += core gui 2 QT += websockets 3 4 greaterThan(QT_MAJOR_VERSION, 4): QT += widgets 5 6 CONFIG += c++11 7 8 # The following define makes your compiler emit warnings if you use 9 # any Qt feature that has been marked deprecated (the exact warnings 10 # depend on your compiler). Please consult the documentation of the 11 # deprecated API in order to know how to port your code away from it. 12 DEFINES += QT_DEPRECATED_WARNINGS 13 14 # You can also make your code fail to compile if it uses deprecated APIs. 15 # In order to do so, uncomment the following line. 16 # You can also select to disable deprecated APIs only up to a certain version of Qt. 17 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 18 19 SOURCES += \ 20 main.cpp \ 21 mainwindow.cpp 22 23 HEADERS += \ 24 mainwindow.h 25 26 FORMS += \ 27 mainwindow.ui 28 29 # Default rules for deployment. 30 qnx: target.path = /tmp/$${TARGET}/bin 31 else: unix:!android: target.path = /opt/$${TARGET}/bin 32 !isEmpty(target.path): INSTALLS += target
main.cpp
1 #include "mainwindow.h" 2 3 #include4 5 int main(int argc, char *argv[]) 6 { 7 QApplication a(argc, argv); 8 MainWindow w; 9 w.show(); 10 return a.exec(); 11 }
mainwindow.h
1 #ifndef MAINWINDOW_H 2 #define MAINWINDOW_H 3 4 #include5 6 #include 7 8 QT_BEGIN_NAMESPACE 9 namespace Ui { class MainWindow; } 10 QT_END_NAMESPACE 11 12 class MainWindow : public QMainWindow 13 { 14 Q_OBJECT 15 16 public: 17 MainWindow(QWidget *parent = nullptr); 18 ~MainWindow(); 19 20 Q_SIGNALS: 21 void closed(); 22 23 private Q_SLOTS: 24 void connectToServer(); 25 void onTextMessageReceived(const QString &message); 26 void closeConnection(); 27 28 public slots: 29 void stopClicked(); 30 void onconnected(); 31 void onSendButtonClicked(); 32 void onCleanButtonClicked(); 33 private: 34 Ui::MainWindow *ui; 35 36 QUrl m_url; 37 QWebSocket m_websocket; 38 bool m_debug; 39 QDateTime *current_date_time; 40 }; 41 #endif // MAINWINDOW_H
mainwindow.cpp
1 #include "mainwindow.h" 2 #include "ui_mainwindow.h" 3 4 MainWindow::MainWindow(QWidget *parent) 5 : QMainWindow(parent) 6 , ui(new Ui::MainWindow) 7 { 8 ui->setupUi(this); 9 connect(ui->linkbutton, SIGNAL(clicked(bool)), this, SLOT(connectToServer())); 10 connect(ui->disconnectbutton, SIGNAL(clicked(bool)), this, SLOT(stopClicked())); 11 connect(ui->sendbutton, SIGNAL(clicked(bool)), this, SLOT(onSendButtonClicked())); 12 connect(ui->cleanButton, SIGNAL(clicked(bool)), this, SLOT(onCleanButtonClicked())); 13 connect(&m_websocket, SIGNAL(connected()), this, SLOT(onconnected())); 14 connect(&m_websocket, SIGNAL(disconnected()), this, SLOT(closeConnection())); 15 connect(&m_websocket, SIGNAL(textMessageReceived(QString)), this, SLOT(onTextMessageReceived(QString))); 16 17 } 18 19 MainWindow::~MainWindow() 20 { 21 delete ui; 22 m_websocket.errorString(); 23 m_websocket.close(); 24 } 25 26 void MainWindow::connectToServer() 27 { 28 QString path = QString("ws://%1:%2").arg(ui->iplineedit->text()).arg(ui->portspinbox->text()); 29 QUrl url = QUrl(path); 30 m_websocket.open(url); 31 } 32 33 void MainWindow::onTextMessageReceived(const QString &message) 34 { 35 QString time = current_date_time->currentDateTime().toString("yyyy.MM.dd hh:mm:ss.zzz ddd"); 36 ui->receivemessageTextEdit->append(time + "\n" + message); 37 } 38 39 void MainWindow::closeConnection() 40 { 41 ui->linkbutton->setEnabled(true); 42 ui->disconnectbutton->setEnabled(false); 43 ui->sendmessagetextedit->setEnabled(false); 44 ui->sendbutton->setEnabled(false); 45 ui->receivemessageTextEdit->setEnabled(false); 46 ui->cleanButton->setEnabled(false); 47 // ui->statusLabel->setText(tr("disconnected")); 48 } 49 50 void MainWindow::stopClicked() 51 { 52 m_websocket.close(); 53 } 54 55 void MainWindow::onconnected() 56 { 57 qDebug() << "hello word!"; 58 // ui->statusLabel->setText(tr("connected")); 59 ui->linkbutton->setEnabled(false); 60 ui->disconnectbutton->setEnabled(true); 61 ui->sendmessagetextedit->setEnabled(true); 62 ui->sendbutton->setEnabled(true); 63 ui->receivemessageTextEdit->setEnabled(true); 64 ui->cleanButton->setEnabled(true); 65 } 66 67 void MainWindow::onSendButtonClicked() 68 { 69 QString msg = ui->sendmessagetextedit->document()->toPlainText(); 70 m_websocket.sendTextMessage(msg); 71 } 72 73 void MainWindow::onCleanButtonClicked() 74 { 75 ui->receivemessageTextEdit->clear(); 76 }
mainwindow.ui
1 <?xml version="1.0" encoding="UTF-8"?> 2"4.0"> 3 <class>MainWindowclass> 4 class="QMainWindow" name="MainWindow"> 5 "geometry"> 6 137 120 80 9561 10406 11"windowTitle"> 14 <string>MainWindowstring> 15 16class="QWidget" name="centralwidget"> 17 152class="QPushButton" name="linkbutton"> 18 30"geometry"> 19 2620 25330 2120 2280 2320 24"text"> 27 <string>连接string> 28 29class="QLabel" name="label"> 31 43"geometry"> 32 3933 3830 3420 3554 3612 37"text"> 40 <string>TextLabelstring> 41 42class="QLineEdit" name="iplineedit"> 44 53"geometry"> 45 5246 51100 4720 48113 4920 50class="QSpinBox" name="portspinbox"> 54 66"geometry"> 55 6256 61230 5720 5881 5922 60"maximum"> 63 6550000 64class="QPushButton" name="disconnectbutton"> 67 79"geometry"> 68 7569 74430 7020 7180 7220 73"text"> 76 <string>断开string> 77 78class="QLabel" name="label_2"> 80 92"geometry"> 81 8882 8730 8380 8454 8512 86"text"> 89 <string>TextLabelstring> 90 91class="QTextEdit" name="sendmessagetextedit"> 93 102"geometry"> 94 10195 10030 96110 97281 9870 99class="QPushButton" name="sendbutton"> 103 115"geometry"> 104 111105 110330 106110 10780 10820 109"text"> 112 <string>发送string> 113 114class="QLabel" name="label_3"> 116 128"geometry"> 117 124118 12330 119210 12054 12112 122"text"> 125 <string>TextLabelstring> 126 127class="QTextEdit" name="receivemessageTextEdit"> 129 138"geometry"> 130 137131 13630 132240 133281 134101 135class="QPushButton" name="cleanButton"> 139 151"geometry"> 140 147141 146330 142240 14380 14420 145"text"> 148 <string>清除string> 149 150class="QMenuBar" name="menubar"> 153 162"geometry"> 154 161155 1600 1560 157561 15822 159class="QStatusBar" name="statusbar"/> 163 164165 166