QWebSocket 客户端范例

描述

The EchoClient example implements a WebSocket client that sends a message to a WebSocket server and dumps the answer that it gets back. This example should ideally be used with the EchoServer example.

Code

我们从连接到 connected() 信号开始。

EchoClient::EchoClient(const QUrl &url, bool debug, QObject *parent) :
    QObject(parent),
    m_url(url),
    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(QUrl(url));
}
					

连接后,打开套接字为给定 url .

void EchoClient::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 连接,我们将收到相同消息。

void EchoClient::onTextMessageReceived(QString message)
{
    if (m_debug)
        qDebug() << "Message received:" << message;
    m_webSocket.close();
}
					

每当收到消息时,我们把它写入输出。