QWebSocket 클라이언트 예제
설명
EchoClient 예제는 WebSocket 서버에 메시지를 보내고 돌아온 응답을 덤프하는 WebSocket 클라이언트를 구현합니다. 이 예제는 EchoServer 예제와 함께 사용하는 것이 이상적입니다.
코드
먼저 `connected()` 신호에 연결합니다.
EchoClient::EchoClient(const QUrl &url, bool debug, QObject *부모) : 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 으로 소켓을 엽니다.
void EchoClient::onConnected() { if (m_debug) qDebug() << "WebSocket connected"; connect(&m_webSocket, &.QWebSocket::textMessageReceived, this, &EchoClient::onTextMessageReceived); m_webSocket.sendTextMessage(QStringLiteral("Hello, world!")); }
클라이언트가 성공적으로 연결되면 `onTextMessageReceived()` 신호에 연결하여 "Hello, world!"를 전송합니다. 에코서버와 연결된 경우 동일한 메시지를 다시 받게 됩니다.
void EchoClient::onTextMessageReceived(QString message) { 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.