首页 > 解决方案 > cpp-httplib https 服务器无法在 Linux 上运行

问题描述

我正在尝试使用 C++ 中的 cpp-httplib 创建一个在 linux 上运行的 HTTPS 服务器。(https://github.com/yhirose/cpp-httplib)当我使用 Windows 时一切正常。但是在 linux 上只有 HTTP 服务器可以工作。似乎 HTTPS 服务器没有打开我不理解的端口......当在终端中键入:sudo netstat -tuplen 时,预期的端口 8080 仅在运行 HTTP 服务器时显示,而不是在运行 HTTPS 服务器时显示。我的防火墙似乎也处于非活动状态: sudo ufw status 给出 Status: inactive
也许我链接了一些错误,但一切似乎都运行良好。我是 C++ 和 Linux 的新手,所以很可能我犯了一个愚蠢的错误。如果这很重要,我只是在 Clion 中运行此代码..

这是 HTTP 服务器的代码(按预期工作和运行):

#include <iostream>
#include "./httplib.h"

int main(void) {
    httplib::Server svr;

    svr.Get("/hi", [](const auto&, auto& res) {
        res.set_content("This is a test response", "text/plain");
    });

    std::cout << "start server..." << std::endl;
    svr.listen("192.158.1.38", 8080);


    std::cin.get();
}

这是 HTTPS 服务器的代码(运行但未打开端口):


#pragma comment (lib, "crypt32")

#define CPPHTTPLIB_OPENSSL_SUPPORT
#include <iostream>
#include "./httplib.h"


// These are shown by Clion that they are not used...
#include </usr/include/openssl/conf.h>
#include </usr/include/openssl/evp.h>
#include </usr/include/openssl/err.h>

int main(void) {

    /// behind svr there have to be keys can not be self signed keys like in 
    httplib::SSLServer svr("./keys/localhost.crt", "./keys/localhost.key");


    svr.Get("/hi", [](const auto&, auto& res) {
        res.set_header("Access-Control-Allow-Origin", "*");
        res.set_content("This is a test response", "text/plain");

    });



    std::cout << "start server..." << std::endl;
    svr.listen("192.158.1.38", 8080);


    std::cin.get();

}

我的 CMakeLists.txt 看起来像这样:

cmake_minimum_required(VERSION 3.20)
project(TLS_Server)

set(CMAKE_CXX_STANDARD 17)

add_executable(TLS_Server main.cpp)


find_package(OpenSSL REQUIRED)


find_package(Threads REQUIRED)
target_link_libraries(TLS_Server PRIVATE OpenSSL::SSL PRIVATE Threads::Threads)

标签: c++linuxserveropenssl

解决方案


好的,正如评论中提到的,问题是找不到证书。我现在已经给出了绝对路径,它工作正常。谢谢!

PS:正如我所说:“可能是一个愚蠢的错误”..


推荐阅读