QT and Symbian

QT v4.x 기반 TcpServer 예제

leo21c 2025. 6. 30. 09:36

Qt 4.x에서도 QTcpServer와 QTcpSocket을 사용하는 기본 구조는 Qt 5/6과 유사하지만, 람다 표현식과 일부 시그널/슬롯 연결 방식이 다릅니다. 아래는 Qt 4.x 호환 TCP 서버 예제입니다:

.

#include <QtCore/QCoreApplication>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
#include <QtCore/QDebug>

class TcpServer : public QObject {
    Q_OBJECT
public:
    TcpServer(QObject *parent = 0) : QObject(parent) {
        server = new QTcpServer(this);
        connect(server, SIGNAL(newConnection()), this, SLOT(onNewConnection()));

        if (server->listen(QHostAddress::Any, 12345)) {
            qDebug() << "서버가 포트 12345에서 대기 중입니다...";
        } else {
            qDebug() << "서버 시작 실패:" << server->errorString();
        }
    }

public slots:
    void onNewConnection() {
        QTcpSocket *clientSocket = server->nextPendingConnection();
        qDebug() << "클라이언트 연결됨:" << clientSocket->peerAddress().toString();

        connect(clientSocket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
        connect(clientSocket, SIGNAL(disconnected()), clientSocket, SLOT(deleteLater()));

        clients.append(clientSocket);
    }

    void onReadyRead() {
        QTcpSocket *clientSocket = qobject_cast<QTcpSocket *>(sender());
        if (!clientSocket) return;

        QByteArray data = clientSocket->readAll();
        qDebug() << "수신된 데이터:" << data;

        clientSocket->write("서버 응답: 메시지 수신 완료\n");
    }

private:
    QTcpServer *server;
    QList<QTcpSocket*> clients;
};

#include "main.moc"

int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);
    TcpServer server;
    return app.exec();
}

 

.pro 파일 설정은 다음과 같이 하시면 됩니다:

QT += core network
CONFIG += console
CONFIG -= app_bundle

 

Qt 4.x에서는 람다 표현식이 지원되지 않기 때문에 SIGNAL()과 SLOT() 매크로를 사용한 전통적인 방식으로 시그널/슬롯을 연결해야 합니다. 이 예제는 콘솔 기반이며, 여러 클라이언트도 처리할 수 있도록 QList<QTcpSocket*>를 사용해 연결을 추적합니다.

LIST