QWebSocketクライアントの例
説明
EchoClient サンプルは、WebSocket サーバーにメッセージを送信し、戻ってきた応答をダンプする WebSocket クライアントを実装しています。この例は、EchoServer の例と一緒に使用するのが理想的です。
コード
まず `connected()` シグナルに接続します。
EchoClient::EchoClient(constQUrl&url, bool debug、 QObject*(parent) : QObject(parent),m_debug(debug) {if(m_debug) qDebug() << "WebSocket server:" << url; コネクト(&m_webSocket, &QWebSocket::connected, this, &EchoClient::onConnected); connect(&m_webSocket, &QWebSocket::disconnected, this, &EchoClient::closed); m_webSocket.open(url); }
接続後、与えられたurl にソケットを開く。
voidEchoClient::onConnected() {if(m_debug) qDebug() << "WebSocket connected"; コネクト(&m_webSocket, &QWebSocket::textMessageReceived, this, &EchoClient::onTextMessageReceived); m_webSocket.sendTextMessage(QStringLiteral("Hello, world!")); }
クライアントが正常に接続されたら、`onTextMessageReceived()`シグナルに接続し、"Hello, world!"を送信します。EchoServerに接続されていれば、同じメッセージが返ってくる。
voidEchoClient::onTextMessageReceived(QStringmessage) {if(m_debug) qDebug() << "Message received:" << message; m_webSocket.close(); }
メッセージを受信するたびに、それを書き出す。
© 2025 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.