Nesta página

Exemplo de cliente QWebSocket

Descrição

O exemplo EchoClient implementa um cliente WebSocket que envia uma mensagem a um servidor WebSocket e exibe a resposta recebida. Idealmente, esse exemplo deve ser usado em conjunto com o exemplo EchoServer.

Código

Começamos conectando-nos ao sinal `connected()`.

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

Após o estabelecimento da conexão, abrimos o socket para o endereço url fornecido.

void EchoClient::onConnected()
{
    if (m_debug)
        qDebug() << "WebSocket connected";
    connect(&m_webSocket, &QWebSocket::textMessageReceived,
            this, &EchoClient::onTextMessageReceived);
    m_webSocket.sendTextMessage(QStringLiteral("Hello, world!"));
}

Quando o cliente estiver conectado com sucesso, conectamos ao sinal `onTextMessageReceived()` e enviamos “Hello, world!”. Se estivermos conectados ao EchoServer, receberemos a mesma mensagem de volta.

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

Sempre que uma mensagem é recebida, nós a gravamos.

© 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.