Qt-QtWebSocket通信功能使用实例

 

 

服务端(QtWebSocketServer):

.pro

 1 QT = websockets
 2 
 3 TARGET = chatserver
 4 CONFIG   += console
 5 CONFIG   -= app_bundle
 6 
 7 TEMPLATE = app
 8 
 9 SOURCES += \
10     main.cpp \
11     chatserver.cpp
12 
13 HEADERS += \
14     chatserver.h
15 
16 EXAMPLE_FILES += chatclient.html
17 
18 target.path = $$[QT_INSTALL_EXAMPLES]/websockets/simplechat
19 INSTALLS += target

main.cpp

 1 #include <QtCore/QCoreApplication>
 2 
 3 #include "chatserver.h"
 4 
 5 int main(int argc, char *argv[])
 6 {
 7     QCoreApplication a(argc, argv);
 8     ChatServer server(1234);
 9 
10     return a.exec();
11 }

 

chatserver.h

 1 /****************************************************************************
 2 **
 3 ** Copyright (C) 2016 Kurt Pattyn <pattyn.kurt@gmail.com>.
 4 ** Contact: https://www.qt.io/licensing/
 5 **
 6 ** This file is part of the QtWebSockets module of the Qt Toolkit.
 7 **
 8 ** $QT_BEGIN_LICENSE:BSD$
 9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** BSD License Usage
18 ** Alternatively, you may use this file under the terms of the BSD license
19 ** as follows:
20 **
21 ** "Redistribution and use in source and binary forms, with or without
22 ** modification, are permitted provided that the following conditions are
23 ** met:
24 **   * Redistributions of source code must retain the above copyright
25 **     notice, this list of conditions and the following disclaimer.
26 **   * Redistributions in binary form must reproduce the above copyright
27 **     notice, this list of conditions and the following disclaimer in
28 **     the documentation and/or other materials provided with the
29 **     distribution.
30 **   * Neither the name of The Qt Company Ltd nor the names of its
31 **     contributors may be used to endorse or promote products derived
32 **     from this software without specific prior written permission.
33 **
34 **
35 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46 **
47 ** $QT_END_LICENSE$
48 **
49 ****************************************************************************/
50 #ifndef CHATSERVER_H
51 #define CHATSERVER_H
52 
53 #include <QtCore/QObject>
54 #include <QtCore/QList>
55 
56 QT_FORWARD_DECLARE_CLASS(QWebSocketServer)
57 QT_FORWARD_DECLARE_CLASS(QWebSocket)
58 QT_FORWARD_DECLARE_CLASS(QString)
59 
60 class ChatServer : public QObject
61 {
62     Q_OBJECT
63 public:
64     explicit ChatServer(quint16 port, QObject *parent = nullptr);
65     ~ChatServer() override;
66 
67 private slots:
68     void onNewConnection();
69     void processMessage(const QString &message);
70     void socketDisconnected();
71 
72 private:
73     QWebSocketServer *m_pWebSocketServer;
74     QList<QWebSocket *> m_clients;
75 };
76 
77 #endif //CHATSERVER_H

chatserver.cpp

  1 /****************************************************************************
  2 **
  3 ** Copyright (C) 2016 Kurt Pattyn <pattyn.kurt@gmail.com>.
  4 ** Contact: https://www.qt.io/licensing/
  5 **
  6 ** This file is part of the QtWebSockets module of the Qt Toolkit.
  7 **
  8 ** $QT_BEGIN_LICENSE:BSD$
  9 ** Commercial License Usage
 10 ** Licensees holding valid commercial Qt licenses may use this file in
 11 ** accordance with the commercial license agreement provided with the
 12 ** Software or, alternatively, in accordance with the terms contained in
 13 ** a written agreement between you and The Qt Company. For licensing terms
 14 ** and conditions see https://www.qt.io/terms-conditions. For further
 15 ** information use the contact form at https://www.qt.io/contact-us.
 16 **
 17 ** BSD License Usage
 18 ** Alternatively, you may use this file under the terms of the BSD license
 19 ** as follows:
 20 **
 21 ** "Redistribution and use in source and binary forms, with or without
 22 ** modification, are permitted provided that the following conditions are
 23 ** met:
 24 **   * Redistributions of source code must retain the above copyright
 25 **     notice, this list of conditions and the following disclaimer.
 26 **   * Redistributions in binary form must reproduce the above copyright
 27 **     notice, this list of conditions and the following disclaimer in
 28 **     the documentation and/or other materials provided with the
 29 **     distribution.
 30 **   * Neither the name of The Qt Company Ltd nor the names of its
 31 **     contributors may be used to endorse or promote products derived
 32 **     from this software without specific prior written permission.
 33 **
 34 **
 35 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 36 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 37 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 38 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 39 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 40 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 41 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 42 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 43 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 44 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 45 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
 46 **
 47 ** $QT_END_LICENSE$
 48 **
 49 ****************************************************************************/
 50 #include "chatserver.h"
 51 
 52 #include <QtWebSockets>
 53 #include <QtCore>
 54 
 55 #include <cstdio>
 56 using namespace std;
 57 
 58 QT_USE_NAMESPACE
 59 
 60 static QString getIdentifier(QWebSocket *peer)
 61 {
 62     return QStringLiteral("%1:%2").arg(peer->peerAddress().toString(),
 63                                        QString::number(peer->peerPort()));
 64 }
 65 
 66 //! [constructor]
 67 ChatServer::ChatServer(quint16 port, QObject *parent) :
 68     QObject(parent),
 69     m_pWebSocketServer(new QWebSocketServer(QStringLiteral("Chat Server"),
 70                                             QWebSocketServer::NonSecureMode,
 71                                             this))
 72 {
 73     if (m_pWebSocketServer->listen(QHostAddress::Any, port))
 74     {
 75         QTextStream(stdout) << "Chat Server listening on port " << port << '\n';
 76         connect(m_pWebSocketServer, &QWebSocketServer::newConnection,
 77                 this, &ChatServer::onNewConnection);
 78     }
 79 }
 80 
 81 ChatServer::~ChatServer()
 82 {
 83     m_pWebSocketServer->close();
 84 }
 85 //! [constructor]
 86 
 87 //! [onNewConnection]
 88 void ChatServer::onNewConnection()
 89 {
 90     auto pSocket = m_pWebSocketServer->nextPendingConnection();
 91     QTextStream(stdout) << getIdentifier(pSocket) << " connected!\n";
 92     pSocket->setParent(this);
 93 
 94     connect(pSocket, &QWebSocket::textMessageReceived,
 95             this, &ChatServer::processMessage);
 96     connect(pSocket, &QWebSocket::disconnected,
 97             this, &ChatServer::socketDisconnected);
 98 
 99     m_clients << pSocket;
100 }
101 //! [onNewConnection]
102 
103 //! [processMessage]
104 void ChatServer::processMessage(const QString &message)
105 {
106     QTextStream(stdout) << " text!" << message.toLocal8Bit()<< " text!\n";
107 
108     QWebSocket *pSender = qobject_cast<QWebSocket *>(sender());
109     for (QWebSocket *pClient : qAsConst(m_clients))
110     {
111         if (pClient == pSender) //don't echo message back to sender
112             pClient->sendTextMessage("ServerReceive:" + message);
113     }
114 }
115 //! [processMessage]
116 
117 //! [socketDisconnected]
118 void ChatServer::socketDisconnected()
119 {
120     QWebSocket *pClient = qobject_cast<QWebSocket *>(sender());
121     QTextStream(stdout) << getIdentifier(pClient) << " disconnected!\n";
122     if (pClient)
123     {
124         m_clients.removeAll(pClient);
125         pClient->deleteLater();
126     }
127 }
128 //! [socketDisconnected]

 

客户端(QtWebSocketClient):

.pro

 1 QT       += core gui websockets
 2 
 3 greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
 4 
 5 CONFIG += c++11
 6 
 7 # The following define makes your compiler emit warnings if you use
 8 # any Qt feature that has been marked deprecated (the exact warnings
 9 # depend on your compiler). Please consult the documentation of the
10 # deprecated API in order to know how to port your code away from it.
11 DEFINES += QT_DEPRECATED_WARNINGS
12 
13 # You can also make your code fail to compile if it uses deprecated APIs.
14 # In order to do so, uncomment the following line.
15 # You can also select to disable deprecated APIs only up to a certain version of Qt.
16 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0
17 
18 SOURCES += \
19     main.cpp \
20     mainwindow.cpp \
21     websocketclient.cpp
22 
23 HEADERS += \
24     mainwindow.h \
25     websocketclient.h
26 
27 FORMS += \
28     mainwindow.ui
29 
30 # Default rules for deployment.
31 qnx: target.path = /tmp/$${TARGET}/bin
32 else: unix:!android: target.path = /opt/$${TARGET}/bin
33 !isEmpty(target.path): INSTALLS += target

 

main.cpp

 1 #include "mainwindow.h"
 2 
 3 #include <QApplication>
 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 <QMainWindow>
 5 #include "websocketclient.h"
 6 
 7 QT_BEGIN_NAMESPACE
 8 namespace Ui { class MainWindow; }
 9 QT_END_NAMESPACE
10 
11 class MainWindow : public QMainWindow
12 {
13     Q_OBJECT
14 
15 public:
16     MainWindow(QWidget *parent = nullptr);
17     ~MainWindow();
18 
19 private slots:
20     void on_pushButton_clicked();
21 
22     void on_pushButton_2_clicked();
23 
24     void on_pushButton_3_clicked();
25 
26 private:
27     Ui::MainWindow *ui;
28     WebSocketClient *m_pClient = nullptr;
29 };
30 #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     this->setWindowTitle(QStringLiteral("QtWebSocketClient"));
10 }
11 
12 MainWindow::~MainWindow()
13 {
14     if(m_pClient)
15     {
16         delete m_pClient;
17         m_pClient = nullptr;
18     }
19     delete ui;
20 }
21 
22 void MainWindow::on_pushButton_clicked()
23 {
24     if(m_pClient)
25     {
26         on_pushButton_3_clicked();
27     }
28     m_pClient = new WebSocketClient(QUrl(QStringLiteral("ws://localhost:1234")), true);
29 
30     QObject::connect(m_pClient, &WebSocketClient::textMessageReceived, [this](const QString &message) {
31         ui->textEdit_2->append("message:" + message);
32         });
33 
34     QObject::connect(m_pClient, &WebSocketClient::errorOccurred, [this](const QString &error) {
35          ui->textEdit_2->append("error:" + error);
36     });
37 }
38 
39 void MainWindow::on_pushButton_2_clicked()
40 {
41     if (m_pClient)
42     {
43         m_pClient->sendTextMessage(QStringLiteral("中文+ok"));// QStringLiteral("中文+ok")
44     }
45 }
46 
47 void MainWindow::on_pushButton_3_clicked()
48 {
49     if(m_pClient)
50     {
51         delete m_pClient;
52         m_pClient = nullptr;
53     }
54 }

 

websocketclient.h

 1 #ifndef WEBSOCKETCLIENT_H
 2 #define WEBSOCKETCLIENT_H
 3 
 4 #include <QtCore/QObject>
 5 #include <QtWebSockets/QWebSocket>
 6 
 7 class WebSocketClient : public QObject
 8 {
 9     Q_OBJECT
10 public:
11     explicit WebSocketClient(const QUrl &url, bool debug = false, QObject *parent = nullptr);
12 
13     qint64 sendTextMessage(QString aValue);
14 signals:
15     void connected();
16     void disconnected();
17     void textMessageReceived(const QString &message);
18     void errorOccurred(const QString &errorString);
19 
20 private Q_SLOTS:
21     void onConnected();
22     void onDisconnected();
23     void onTextMessageReceived(const QString &message);
24     void onError(QAbstractSocket::SocketError error);
25 
26 private:
27     QWebSocket m_webSocket;
28     QUrl m_url;
29     bool m_debug;
30 };
31 
32 #endif // WEBSOCKETCLIENT_H

 

websocketclient.cpp

 1 #include "websocketclient.h"
 2 #include <QDebug>
 3 
 4 WebSocketClient::WebSocketClient(const QUrl &url, bool debug, QObject *parent)
 5     :QObject(parent),
 6     m_url(url),
 7     m_debug(debug)
 8 {
 9     connect(&m_webSocket, &QWebSocket::connected, this, &WebSocketClient::onConnected);
10     connect(&m_webSocket, &QWebSocket::disconnected, this, &WebSocketClient::onDisconnected);
11     connect(&m_webSocket, &QWebSocket::textMessageReceived, this, &WebSocketClient::onTextMessageReceived);
12     connect(&m_webSocket, static_cast<void(QWebSocket::*)(QAbstractSocket::SocketError)>(&QWebSocket::error), this, &WebSocketClient::onError);
13     m_webSocket.open(QUrl(url));
14 }
15 
16 qint64 WebSocketClient::sendTextMessage(QString aValue)
17 {
18     return m_webSocket.sendTextMessage(aValue);
19 }
20 
21 void WebSocketClient::onConnected()
22 {
23     qDebug() << "WebSocket connected";
24     emit connected();
25 }
26 
27 void WebSocketClient::onDisconnected()
28 {
29     qDebug() << "WebSocket disconnected";
30     emit disconnected();
31 }
32 
33 void WebSocketClient::onTextMessageReceived(const QString &message)
34 { 
35     qDebug() << QString(message.toLocal8Bit());
36     emit textMessageReceived(QString(message.toLocal8Bit()));
37 }
38 
39 void WebSocketClient::onError(QAbstractSocket::SocketError error)
40 {
41     Q_UNUSED(error)
42     qDebug() << "WebSocket error:" << m_webSocket.errorString();
43     emit errorOccurred(m_webSocket.errorString());
44 }

 

posted on 2026-01-31 12:16  疯狂delphi  阅读(4)  评论(0)    收藏  举报

导航