自学内容网 自学内容网

qt QWebSocketServer详解

1、概述

QWebSocketServer 是 Qt 框架中用于处理 WebSocket 服务器端的类。它允许开发者创建 WebSocket 服务器,接受客户端的连接,并与之进行双向通信。WebSocket 是一种在单个 TCP 连接上进行全双工通讯的协议,它使得客户端和服务器之间的数据交换变得更加简单和高效。

QWebSocketServer 提供了 WebSocket 服务器所需的基本功能,包括监听端口、接受连接、发送和接收消息等。它通常与 QWebSocket 类一起使用,后者表示一个 WebSocket 连接,并提供了与该连接进行交互的方法。

2、重要方法

QWebSocketServer 类的重要方法包括但不限于:

  • QWebSocketServer(const QString &serverName, QWebSocketServer::NonSecureMode serverType = NonSecureMode, QObject *parent = nullptr): 构造函数,创建一个 WebSocket 服务器实例。
  • bool listen(const QHostAddress &address = QHostAddress::Any, quint16 port = 0): 使服务器监听指定的地址和端口。
  • void close(): 关闭服务器,停止监听连接。
  • QList<QWebSocket *> clients() const: 返回当前连接到服务器的所有客户端列表。
  • bool hasPendingConnections() const: 检查是否有等待接受的连接。
  • QWebSocket *nextPendingConnection(): 接受一个等待中的连接,并返回一个新的 QWebSocket 对象来表示该连接。
  • QString serverName() const: 返回服务器的名称。
  • QWebSocketServer::WebSocketServerState state() const: 返回服务器的当前状态(如监听中、关闭等)。
3、重要信号

QWebSocketServer 类的重要信号包括:

  • newConnection(): 当有新的客户端连接请求时发出。
  • acceptError(QAbstractSocket::SocketErrors socketError):当连接出现错误时发出信号。
  • serverError(0WebSocketProtocol::CloseCode closeCode):当服务器发生错误时发出信号。

4、常用枚举类型

以下是 QWebSocketServer类中一些常用的枚举类型及其简要介绍:
QWebSocketServer::SslMode: SSL 模式。

  • SslMode::NonSecureMode:不支持SSL/TLS
  • SslMode::SecureMode:支持SSL/TLS

5、实现 SSL/TLS 加密
QWebSocketServer 支持 SSL/TLS 加密以提供安全的WebSocket 连接。为了实现SSL/TLS,您需要配置合适的证书和密钥:

QWebSocketServer server("Secure WebSocket Server", QWebSocketServer::SecureMode);
QSslConfiguration sslConfiguration;
sslConfiguration.setLocalCertificate(QStringLiteral("server.crt"));
sslConfiguration.setPrivateKey(QStringLiteral("server.key"));
server.setSslConfiguration(sslConfiguration);

if (server.listen(QHostAddress::Any, 1234)) {
    qDebug() << "Secure WebSocket server listening on port 1234.";
}

//.h
class MyWebSocketClient : public QObject {
    Q_OBJECT

public:
    MyWebSocketClient(QObject *parent = nullptr) : QObject(parent), m_pWebSocket(nullptr) {
        m_pWebSocket = new QWebSocket();

        // 连接服务器
        QUrl serverUrl("ws://localhost:12345"); // 替换为实际的服务器URL
        m_pWebSocket->open(serverUrl);

        // 连接信号和槽
        connect(m_pWebSocket, &QWebSocket::connected, this, &MyWebSocketClient::onConnected);
        connect(m_pWebSocket, &QWebSocket::disconnected, this, &MyWebSocketClient::onDisconnected);
        connect(m_pWebSocket, QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error), this, &MyWebSocketClient::onError);
        connect(m_pWebSocket, &QWebSocket::textMessageReceived, this, &MyWebSocketClient::onTextMessageReceived);
    }

    ~MyWebSocketClient() {
        m_pWebSocket->close();
    }

private slots:
    void onConnected() {
        qDebug() << "Connected to WebSocket server";

        // 发送消息给服务器
        QString message = "Hello, WebSocket server!";
        m_pWebSocket->sendTextMessage(message);
    }

    void onDisconnected() {
        qDebug() << "Disconnected from WebSocket server";
    }

    void onError(QAbstractSocket::SocketError error) {
        qDebug() << "WebSocket error:" << error;
    }

    void onTextMessageReceived(QString message) {
        qDebug() << "Received message from WebSocket server:" << message;
    }

private:
    QWebSocket *m_pWebSocket;
};



class WebSocketServer : public QObject
{
    Q_OBJECT

public:
    explicit WebSocketServer(quint16 port=12345, QObject *parent = nullptr);
    ~WebSocketServer();

private slots:
    void onNewConnection();
    void onTextMessageReceived(const QString &message);
    void onDisconnected();

private:
    QWebSocketServer *m_server;
    QList<QWebSocket *> m_clients;
};



/************************************/
//.cpp
WebSocketServer::WebSocketServer(quint16 port, QObject *parent)
    : QObject(parent),
      m_server(new QWebSocketServer(QStringLiteral("WebSocket Server"), QWebSocketServer::NonSecureMode, this))
{
    if (m_server->listen(QHostAddress::Any, port)) {
        qDebug() << "WebSocket server listening on port" << port;
        connect(m_server, &QWebSocketServer::newConnection, this, &WebSocketServer::onNewConnection);
    } else {
        qDebug() << "Error: Unable to start the WebSocket server:" << m_server->errorString();
    }
}

WebSocketServer::~WebSocketServer()
{
    m_server->close();
    qDeleteAll(m_clients.begin(), m_clients.end());
}

void WebSocketServer::onNewConnection()
{
    QWebSocket *client = m_server->nextPendingConnection();
    connect(client, &QWebSocket::textMessageReceived, this, &WebSocketServer::onTextMessageReceived);
    connect(client, &QWebSocket::disconnected, this, &WebSocketServer::onDisconnected);
    m_clients << client;
    qDebug() << "New client connected.";
}

void WebSocketServer::onTextMessageReceived(const QString &message)
{
    QWebSocket *client = qobject_cast<QWebSocket *>(sender());
    qDebug() << "Message received:" << message;
    client->sendTextMessage("Echo: " + message);
}

void WebSocketServer::onDisconnected()
{
    QWebSocket *client = qobject_cast<QWebSocket *>(sender());
    if (client) {
        m_clients.removeAll(client);
        client->deleteLater();
        qDebug() << "Client disconnected.";
    }
}


觉得有帮助的话,打赏一下呗。。

           


原文地址:https://blog.csdn.net/ckg3824278/article/details/143603663

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!