간단한 HTTP 서버

HTTP 서버를 설정하는 간단한 예제입니다.

간단한 HTTP 서버는 QHttpServer 클래스를 사용하여 HTTP 서버를 설정하는 방법을 보여줍니다. 이 서버는 두 개의 소켓, 즉 하나의 TCP 소켓과 하나의 SSL 소켓을 수신합니다. route () 함수를 사용하는 방법을 보여주기 위해 다양한 콜백이 설정되어 있습니다.

QHttpServer 객체가 생성되고 간단한 route() 함수는 Hello world 을 반환하여 "/" 경로를 처리합니다:

QCoreApplication app(argc, argv);

QHttpServer httpServer;
httpServer.route("/", []() {
    return "Hello world";
});

그런 다음 서버의 자산을 클라이언트에 제공하는 콜백을 등록합니다:

httpServer.route("/assets/<arg>", [] (const QUrl &url) {
    return QHttpServerResponse::fromFile(u":/assets/"_s + url.path());
});

여기서는 QHttpServerRequest 객체를 사용하여 클라이언트의 IP 주소를 반환합니다:

httpServer.route("/remote_address", [](const QHttpServerRequest &request) {
    return request.remoteAddress().toString();
});

경로 중 하나인 "/auth" 의 경우 기본 HTTP 인증이 사용됩니다:

httpServer.route("/auth", [](const QHttpServerRequest &request) {
    auto auth = request.value("authorization").simplified();

    if (auth.size() > 6 && auth.first(6).toLower() == "basic ") {
        auto token = auth.sliced(6);
        auto userPass = QByteArray::fromBase64(token);

        if (auto colon = userPass.indexOf(':'); colon > 0) {
            auto userId = userPass.first(colon);
            auto password = userPass.sliced(colon + 1);

            if (userId == "Aladdin" && password == "open sesame")
                return QHttpServerResponse("text/plain", "Success\n");
        }
    }
    QHttpServerResponse resp("text/plain", "Authentication required\n",
                             QHttpServerResponse::StatusCode::Unauthorized);
    auto h = resp.headers();
    h.append(QHttpHeaders::WellKnownHeader::WWWAuthenticate,
             R"(Basic realm="Simple example", charset="UTF-8")");
    resp.setHeaders(std::move(h));
    return std::move(resp);
});

그런 다음 addAfterRequestHandler() 함수를 사용하여 route()에 등록된 콜백에 의해 처리된 후 QHttpServerResponse 객체를 변경하여 응답에 HTTP 헤더를 추가합니다:

httpServer.addAfterRequestHandler(&httpServer, [](const QHttpServerRequest &, QHttpServerResponse &resp) {
    auto h = resp.headers();
    h.append(QHttpHeaders::WellKnownHeader::Server, "Qt HTTP Server");
    resp.setHeaders(std::move(h));
});

포트를 수신 중인 QTcpServerbind() 함수를 사용하여 HTTP 서버에 바인딩됩니다:

auto tcpserver = std::make_unique<QTcpServer>();if (!tcpserver->listen() || !httpServer.bind(tcpserver.get()))) {    qWarning() << QCoreApplication::translate("QHttpServerExample",
                                             "서버가 포트에서 수신 대기하지 못했습니다."); return-1; }quint16 port =  tcpserver->serverPort(); tcpserver.release();

그런 다음 QSslConfiguration 을 사용하여 QHttpServer 에 HTTPS 트래픽을 전송하기 위한 SSL 구성을 만듭니다:

QSslConfiguration conf = QSslConfiguration::defaultConfiguration();const auto sslCertificateChain =.  QSslCertificate::fromPath(QStringLiteral(":/assets/certificate.crt"));if (sslCertificateChain.empty()) {    qWarning() << QCoreApplication::translate("QHttpServerExample",
                                             "파일에서 SSL 인증서를 검색할 수 없습니다."); return-1; }QFile privateKeyFile(QStringLiteral(":/assets/private.key"));if (!privateKeyFile.open(QIODevice::ReadOnly)) {    qWarning() << QCoreApplication::translate("QHttpServerExample",
                                             "읽을 파일을 열 수 없습니다: %1") . arg(privateKeyFile.errorString()); return-1; } conf.setLocalCertificate(sslCertificateChain.front()); conf.setPrivateKey(QSslKey(&privateKeyFile, QSsl::Rsa)); privateKeyFile.close();auto sslserver = std::make_unique<QSslServer>();  sslserver->setSslConfiguration(conf);if (!sslserver->listen() || !httpServer.bind(sslserver.get()))) {    qWarning() << QCoreApplication::translate("QHttpServerExample",
                                             "서버가 포트에서 수신 대기하지 못했습니다."); 반환-1; }quint16 sslPort =  sslserver->serverPort(); sslserver.release();

모든 설정이 완료되면 이제 들어오는 요청을 처리하기만 하면 됩니다:

return app.exec();

Files:

파일: 이미지:

© 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.