간단한 HTTP 서버

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

이 예는 QHttpServer 클래스를 사용하여 서버를 설정하는 방법을 보여줍니다. 서버는 bind() 함수를 사용하여 포트를 수신하는 QTcpServer 에 바인딩되며, route() 함수는 여러 다른 수신 URL 각각에 대한 핸들러를 추가하는 데 사용됩니다. URL 중 하나인 "/auth"의 경우 기본 HTTP 인증이 사용됩니다.

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();

위의 예제에서 QSslConfigurationQHttpServer 에 HTTPS 트래픽을 제공하기 위한 SSL 구성을 만드는 방법을 보여주기 위해 사용되었습니다.

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

위의 예는 QHttpServeraddAfterRequestHandler() 함수를 사용하여 QHttpServerResponse 객체가 route() 함수에 의해 처리된 후 변경하는 방법을 보여줍니다. HTTP 헤더를 응답에 추가하는 방법을 보여줍니다.

파일:

이미지:

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