友情链接:
C++网络库cpp-netlib的安装
简单介绍
cpp-netlib是基于asio库的http网络库, 包含了HTTP/HTTPS客户端、服务端的接口支持
cpp-netlib安装位置
头文件一般安装在
1
| ${CMAKE_INSTALL_PREFIX}/include/boost/network
|
库文件(.a, .so)一般在
1
| ${CMAKE_INSTALL_PREFIX}/lib/
|
其中CMAKE_INSTALL_PREFIX
是执行安装脚本时候设定的路径, 比如 CMAKE_INSTALL_PREFIX=/usr/local时, 以上的目录则变为
1 2
| /usr/local/include/boost/network /usr/local/lib
|
写服务端程序时
需要包含的头文件
1 2
| #include <network/uri.hpp> #include <boost/network/protocol/http/server.hpp>
|
需要引入的库
1 2 3 4 5
| target_link_libraries(app boost_system network-uri cppnetlib-server-parsers )
|
其中cppnetlib-server-parsers
时服务端解析请求时所需要的库
network-uri
是我们自己在解析请求参数的path、query、host、port、protocol等参数需要用到的库
boost_system
是cppnetlib-server-parsers以及我们在使用cpp-netlib是调用的一些借口内部依赖的库
示例代码(C++11, cpp-netlib 版本: 0.12.0)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| #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; SSPD_LOG_INFO << "[REQ] Destination: " << request.destination; SSPD_LOG_INFO << "[REQ] Body: " << request.body; SSPD_LOG_INFO << "[REQ] 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; }
|
所用到的工具库:
nlohmann/json
sspdlog