Exemple de client QWebSocket
Description
L'exemple EchoClient implémente un client WebSocket qui envoie un message à un serveur WebSocket et affiche la réponse qu'il reçoit. Cet exemple est destiné à être utilisé, dans l'idéal, avec l'exemple EchoServer.
Code
Nous commençons par nous connecter au signal `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);
}Une fois la connexion établie, nous ouvrons le socket vers l'adresse url indiquée.
void EchoClient::onConnected()
{
if (m_debug)
qDebug() << "WebSocket connected";
connect(&m_webSocket, &QWebSocket::textMessageReceived,
this, &EchoClient::onTextMessageReceived);
m_webSocket.sendTextMessage(QStringLiteral("Hello, world!"));
}Une fois le client connecté, nous nous connectons au signal `onTextMessageReceived()` et envoyons « Hello, world ! ». Si la connexion avec EchoServer est établie, nous recevrons le même message en retour.
void EchoClient::onTextMessageReceived(QString message)
{
if (m_debug)
qDebug() << "Message received:" << message;
m_webSocket.close();
}À chaque fois qu'un message est reçu, nous l'affichons.
© 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.