QWebSocket 클라이언트 예제
설명
EchoClient 예제는 WebSocket 서버로 메시지를 전송하고, 수신한 응답을 출력하는 WebSocket 클라이언트를 구현합니다. 이 예제는 가급적 EchoServer 예제와 함께 사용하는 것이 좋습니다.
코드
먼저 `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);
}연결이 완료된 후, 지정된 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!"를 전송합니다. EchoServer에 연결된 경우, 동일한 메시지를 다시 수신하게 됩니다.
void EchoClient::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.