Ejemplo de cliente QWebSocket
Descripción
El ejemplo EchoClient implementa un cliente WebSocket que envía un mensaje a un servidor WebSocket y vuelca la respuesta que recibe. Este ejemplo debería usarse idealmente con el ejemplo EchoServer.
Código
Comenzamos 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 la conexión, abrimos el socket a la dirección url.
void EchoClient::onConnected() { if (m_debug) qDebug() << "WebSocket connected"; connect(&m_webSocket, &QWebSocket::textMessageReceived, this, &EchoClient::onTextMessageReceived); m_webSocket.sendTextMessage(QStringLiteral("¡Hola, mundo!")); }
Cuando el cliente se conecta con éxito, nos conectamos a la señal `onTextMessageReceived()`, y enviamos "¡Hola, mundo!". Si estamos conectados con el EchoServer, recibiremos el mismo mensaje de vuelta.
void EchoClient::onTextMessageReceived(QString mensaje) { 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.