QWebSocket 客户端示例

说明

EchoClient 示例实现了一个 WebSocket 客户端,它向 WebSocket 服务器发送消息,并转储得到的回复。该示例最好与 EchoServer 示例一起使用。

代码

我们首先连接到 `connected()` 信号。

EchoClient::EchoClient(constQUrl&url, bool  debugQObject*parent) :   QObject(parent),m_debug(debug) {if(m_debug)        qDebug() << "WebSocket server:" << url;
    connect(&m_webSocket, &EchoClient)QWebSocket::connected, this, &EchoClient::onConnected); connect(&m_webSocket, &m_webSocket.open(url); }QWebSocket::disconnected, this, &EchoClient::closed); m_webSocket.open(url); }

连接完成后,我们将打开连接到给定url 的套接字。

voidEchoClient::onConnected() {if(m_debug)        qDebug() << "WebSocket connected";
    连接(&m_webSocket, &QWebSockettextMessageReceived, this, &EchoClient::onTextMessageReceived); m_webSocket.sendTextMessage(QStringLiteral("你好,世界!")); }

客户端连接成功后,我们连接到 `onTextMessageReceived()` 信号,并发送 "Hello, world!"。如果与 EchoServer 连接,我们将收到同样的回传信息。

voidEchoClient::onTextMessageReceived(QStringmessage) {if(m_debug)        qDebug() << "Message received:" << message;
    m_webSocket.close(); }

每当收到一条信息,我们就将其写出。

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.