웹소켓 서버 예제
설명
echoserver 예제는 전송되는 모든 것을 에코백하는 WebSocket 서버를 구현합니다.
코드
먼저 QWebSocketServer (`new QWebSocketServer()`)를 생성합니다. 생성 후 지정된 port 에서 모든 로컬 네트워크 인터페이스(`QHostAddress::Any`)를 수신 대기합니다.
에코서버::에코서버(quint16 포트, 부울 디버그, QObject *부모) : QObject(부모),m_pWebSocketServer(new QWebSocketServer(QStringLiteral("Echo Server"), QWebSocketServer::NonSecureMode, this)),m_debug(debug) { if (m_pWebSocketServer->listen(QHostAddress::Any, port)) { if (m_debug) qDebug() << "Echoserver listening on port" << port; connect(m_pWebSocketServer, &.QWebSocketServer::newConnection, this, &EchoServer::onNewConnection); connect(m_pWebSocketServer, &QWebSocketServer::closed, this, &EchoServer::closed); } }
수신에 성공하면 `newConnection()` 신호를 `onNewConnection()` 슬롯에 연결합니다. 새로운 웹소켓 클라이언트가 서버에 연결될 때마다 `newConnection()` 신호가 발생합니다.
void EchoServer::onNewConnection() { QWebSocket *pSocket = m_pWebSocketServer->nextPendingConnection(); connect(pSocket, &QWebSocket::textMessageReceived, this, &EchoServer::processTextMessage); connect(pSocket, &QWebSocket::binaryMessageReceived, this, &EchoServer::processBinaryMessage); connect(pSocket, &QWebSocket::disconnected, this, &EchoServer::socketDisconnected); m_clients << pSocket; }
새 연결이 수신되면 QWebSocket 클라이언트가 검색되고(`nextPendingConnection()`), 관심 있는 신호가 우리 슬롯에 연결됩니다(`textMessageReceived()`, `binaryMessageReceived()` 및 `disconnected()`). 클라이언트 소켓은 나중에 사용할 경우를 대비해 목록에 기억됩니다(이 예제에서는 아무 작업도 수행하지 않았습니다).
void EchoServer::processTextMessage(QString message) { QWebSocket *pClient = qobject_cast<QWebSocket *>(sender()); if (m_debug) qDebug() << "Message received:" << message; if (pClient) { pClient->sendTextMessage(message); } }
processTextMessage()`가 트리거될 때마다 발신자를 검색하고 유효하면 원래 메시지(`sendTextMessage()`)를 다시 보냅니다. 바이너리 메시지도 마찬가지입니다.
void EchoServer::processBinaryMessage(QByteArray message) { QWebSocket *pClient = qobject_cast<QWebSocket *>(sender()); if (m_debug) qDebug() << "Binary Message received:" << message; if (pClient) { pClient->sendBinaryMessage(message); } }
유일한 차이점은 이제 메시지가 QString 대신 QByteArray 라는 것입니다.
void EchoServer::socketDisconnected() { QWebSocket *pClient = qobject_cast<QWebSocket *>(sender()); if (m_debug) qDebug() << "socketDisconnected:" << pClient; if (pClient) { m_clients.removeAll(pClient); pClient->deleteLater(); } }
소켓의 연결이 끊어질 때마다 클라이언트 목록에서 해당 소켓을 제거하고 소켓을 삭제합니다. 참고: 소켓을 삭제하려면 `deleteLater()`를 사용하는 것이 가장 좋습니다.
© 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.