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 #include 
 4 
 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 #include 
 5 
 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    
  7     0
  8     0
  9     800
 10     600
 11    
 12   
 13   "windowTitle">
 14    <string>MainWindowstring>
 15   
 16   class="QWidget" name="centralwidget">
 17    class="QLabel" name="label">
 18     "geometry">
 19      
 20       30
 21       40
 22       54
 23       12
 24      
 25     
 26     "text">
 27      <string>TextLabelstring>
 28     
 29    
 30    class="QSpinBox" name="monitorSpinBox">
 31     "geometry">
 32      
 33       100
 34       30
 35       101
 36       22
 37      
 38     
 39     "maximum">
 40      50000
 41     
 42    
 43    class="QPushButton" name="startButton">
 44     "geometry">
 45      
 46       220
 47       30
 48       80
 49       20
 50      
 51     
 52     "text">
 53      <string>启动string>
 54     
 55    
 56    class="QPushButton" name="stopButton">
 57     "geometry">
 58      
 59       320
 60       30
 61       80
 62       20
 63      
 64     
 65     "text">
 66      <string>停止string>
 67     
 68    
 69    class="QTextEdit" name="sendTextedit">
 70     "geometry">
 71      
 72       30
 73       80
 74       361
 75       70
 76      
 77     
 78    
 79    class="QPushButton" name="sendButton">
 80     "geometry">
 81      
 82       410
 83       80
 84       80
 85       20
 86      
 87     
 88     "text">
 89      <string>发送string>
 90     
 91    
 92    class="QTextEdit" name="receiveTextEdit">
 93     "geometry">
 94      
 95       30
 96       220
 97       351
 98       211
 99      
100     
101    
102    class="QLabel" name="label_2">
103     "geometry">
104      
105       30
106       200
107       54
108       12
109      
110     
111     "text">
112      <string>TextLabelstring>
113     
114    
115    class="QLabel" name="label_3">
116     "geometry">
117      
118       390
119       200
120       54
121       12
122      
123     
124     "text">
125      <string>TextLabelstring>
126     
127    
128    class="QPushButton" name="cleanButton">
129     "geometry">
130      
131       630
132       190
133       80
134       20
135      
136     
137     "text">
138      <string>清除string>
139     
140    
141    class="QListWidget" name="linkclientListWidget">
142     "geometry">
143      
144       410
145       230
146       256
147       192
148      
149     
150    
151   
152   class="QMenuBar" name="menubar">
153    "geometry">
154     
155      0
156      0
157      800
158      22
159     
160    
161   
162   class="QStatusBar" name="statusbar"/>
163  
164  
165  
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 #include 
 4 
 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 #include 
 5 
 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    
  7     0
  8     0
  9     561
 10     406
 11    
 12   
 13   "windowTitle">
 14    <string>MainWindowstring>
 15   
 16   class="QWidget" name="centralwidget">
 17    class="QPushButton" name="linkbutton">
 18     "geometry">
 19      
 20       330
 21       20
 22       80
 23       20
 24      
 25     
 26     "text">
 27      <string>连接string>
 28     
 29    
 30    class="QLabel" name="label">
 31     "geometry">
 32      
 33       30
 34       20
 35       54
 36       12
 37      
 38     
 39     "text">
 40      <string>TextLabelstring>
 41     
 42    
 43    class="QLineEdit" name="iplineedit">
 44     "geometry">
 45      
 46       100
 47       20
 48       113
 49       20
 50      
 51     
 52    
 53    class="QSpinBox" name="portspinbox">
 54     "geometry">
 55      
 56       230
 57       20
 58       81
 59       22
 60      
 61     
 62     "maximum">
 63      50000
 64     
 65    
 66    class="QPushButton" name="disconnectbutton">
 67     "geometry">
 68      
 69       430
 70       20
 71       80
 72       20
 73      
 74     
 75     "text">
 76      <string>断开string>
 77     
 78    
 79    class="QLabel" name="label_2">
 80     "geometry">
 81      
 82       30
 83       80
 84       54
 85       12
 86      
 87     
 88     "text">
 89      <string>TextLabelstring>
 90     
 91    
 92    class="QTextEdit" name="sendmessagetextedit">
 93     "geometry">
 94      
 95       30
 96       110
 97       281
 98       70
 99      
100     
101    
102    class="QPushButton" name="sendbutton">
103     "geometry">
104      
105       330
106       110
107       80
108       20
109      
110     
111     "text">
112      <string>发送string>
113     
114    
115    class="QLabel" name="label_3">
116     "geometry">
117      
118       30
119       210
120       54
121       12
122      
123     
124     "text">
125      <string>TextLabelstring>
126     
127    
128    class="QTextEdit" name="receivemessageTextEdit">
129     "geometry">
130      
131       30
132       240
133       281
134       101
135      
136     
137    
138    class="QPushButton" name="cleanButton">
139     "geometry">
140      
141       330
142       240
143       80
144       20
145      
146     
147     "text">
148      <string>清除string>
149     
150    
151   
152   class="QMenuBar" name="menubar">
153    "geometry">
154     
155      0
156      0
157      561
158      22
159     
160    
161   
162   class="QStatusBar" name="statusbar"/>
163  
164  
165  
166 

相关