QWebSocket 客户端示例
说明
EchoClient 示例实现了一个 WebSocket 客户端,该客户端向 WebSocket 服务器发送消息,并输出收到的响应。该示例最好与 EchoServer 示例配合使用。
代码
首先,我们连接到 `connected()` 信号。
EchoClient::EchoClient(constQUrl&url, booldebug,QObject*parent) :
QObject(parent),
m_debug(debug)
{
if(m_debug)
qDebug() << "WebSocket server:" << url;
connect(&m_webSocket, &QWebSocket::connected, this, &EchoClient::onConnected);
connect(&m_webSocket, &QWebSocket::disconnected, this, &EchoClient::closed);
m_webSocket.open(url);
}连接建立后,我们向指定的url 打开套接字。
voidEchoClient::onConnected()
{
if(m_debug)
qDebug() << "WebSocket connected";
connect(&m_webSocket, &QWebSocket::textMessageReceived,
this, &EchoClient::onTextMessageReceived);
m_webSocket.sendTextMessage(QStringLiteral("Hello, world!"));
}当客户端成功连接后,我们会连接到 `onTextMessageReceived()` 信号,并发送“Hello, world!”。如果连接到了 EchoServer,我们将收到相同的消息作为响应。
voidEchoClient::onTextMessageReceived(QString message)
{
if(m_debug)
qDebug() << "Message received:" << message;
m_webSocket.close();
}每当收到一条消息时,我们就会将其写出。
© 2026 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.