QWebSocket クライアントの例
説明
EchoClient のサンプルは、WebSocket サーバーにメッセージを送信し、返ってきた応答を出力する WebSocket クライアントを実装しています。このサンプルは、EchoServer のサンプルと組み合わせて使用するのが理想的です。
コード
まず、`connected()`シグナルに接続します。
EchoClient::EchoClient(constQUrl&url, booldebug,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);
}接続後、指定されたurl へのソケットを開きます。
voidEchoClient::onConnected()
{
if(m_debug)
qDebug() << "WebSocket connected";
connect(&m_webSocket, &QWebSocket::textMessageReceived,
this, &EchoClient::onTextMessageReceived);
m_webSocket.sendTextMessage(QStringLiteral("Hello, world!"));
}クライアントの接続に成功すると、`onTextMessageReceived()` シグナルに接続し、「Hello, world!」を送信します。EchoServer に接続されている場合、同じメッセージが返ってきます。
voidEchoClient::onTextMessageReceived(QString message)
{
if(m_debug)
qDebug() << "Message received:" << message;
m_webSocket.close();
}メッセージを受信するたびに、それを書き出します。
© 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.