当前位置: 首页 > 工具软件 > cpp-netlib > 使用案例 >

C++ 网络库 cpp-netlib的简单使用

公良弘毅
2023-12-01

详情还请移步至个人博客

逗神大人的个人小站

示例代码 (C++11, cpp-netlib版本:0.12.0)

需要链接库文件

target_link_libraries(app
    boost_system
    network-uri
    cppnetlib-server-parsers
    )
#include <network/uri.hpp>
#include <nlohmann/json.hpp>
#include <sspdlog/sspdlog.h>
#include <boost/network/protocol/http/server.hpp>

namespace http = boost::network::http;

using json = nlohmann::json;

struct Controller;

using SimpleHTTPServer = http::server<Controller>;

struct Controller {
    void operator() (SimpleHTTPServer::request const &request,
                     SimpleHTTPServer::connection_ptr response) {
        if( request.method == "GET") {
            response->set_status(SimpleHTTPServer::connection::ok);
            response->set_headers(std::map<std::string, std::string> {
                                      {"Content-Type", "application/json;charset=utf-8"}
                                  });
            response->write(json{
                                {"say", "Who are you?"}
                            }.dump(2));
        }

        SSPD_LOG_INFO << "[REQ] Source: " << request.source; /// client info: <ip>:<port>
        SSPD_LOG_INFO << "[REQ] Destination: " << request.destination; /// path: /index?name=sb
        SSPD_LOG_INFO << "[REQ] Body: " << request.body; /// Body data: {"data": [0, 0]}
        SSPD_LOG_INFO << "[REQ] Version: " /// HTTP version
                      << static_cast<unsigned>(request.http_version_major)
                      << '.'
                      << static_cast<unsigned>(request.http_version_minor);

        network::uri uri("http://localhost:9090" + request.destination);

        SSPD_LOG_INFO << "[URI] Host: " << uri.host();
        SSPD_LOG_INFO << "[URI] Port: " << uri.port<unsigned>();
        SSPD_LOG_INFO << "[URI] Query: " << uri.query();
        SSPD_LOG_INFO << "[URI] Route: " << uri.path();

    }

    void log(SimpleHTTPServer::string_type const &info) {
        std::cerr << "ERROR: " << info << '\n';
    }
};

int main(int,char**)
{

    Controller control{};
    SimpleHTTPServer::options options(control);
    SimpleHTTPServer server(options.address("0.0.0.0").port("9090"));
    server.run();

    return 0;
}

 类似资料: