En esta página

Ejemplo de cliente QWebSocket

Descripción

El ejemplo EchoClient implementa un cliente WebSocket que envía un mensaje a un servidor WebSocket y muestra la respuesta que recibe. Lo ideal es utilizar este ejemplo junto con el ejemplo EchoServer.

Código

Empezamos conectándonos a la señal `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);
}

Tras establecer la conexión, abrimos el socket a la dirección url indicada.

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

Cuando el cliente se conecta correctamente, nos conectamos a la señal `onTextMessageReceived()` y enviamos «Hello, world!». Si estamos conectados con el EchoServer, recibiremos el mismo mensaje de vuelta.

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

Cada vez que se recibe un mensaje, lo escribimos.

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