Boost.Asio学习之简单的HTTP服务器

代码见:http://www.boost.org/doc/libs/1_61_0/doc/html/boost_asio/examples/cpp11_examples.html
或者:https://github.com/NearXdu/AsioLearn

这是boost.asio的example中比较大的一示例了,主要是HTTP协议的在应用层的业务比较复杂,不过提供的例子实现了简单的HTTP服务器。

1.Main

抛开业务不说,http服务器本质上来说是一个TCP服务器。因此,根据看的那么多boost.asio官方提供的example,它的套路还是比较单一的:

#include 
#include 
#include 
#include "http_server.hpp"

int main(int argc, char* argv[])
{
    try
    {
    // Check command line arguments.
    if (argc != 4)
    {
        std::cerr << "Usage: http_server 
\n"; std::cerr << " For IPv4, try:\n"; std::cerr << " receiver 0.0.0.0 80 .\n"; std::cerr << " For IPv6, try:\n"; std::cerr << " receiver 0::0 80 .\n"; return 1; } // Initialise the server. http::server::server s(argv[1], argv[2], argv[3]); // Run the server until stopped. s.run(); } catch (std::exception& e) { std::cerr << "exception: " << e.what() << "\n"; } return 0; }

2.HTTP_SERVER类

在server的构造函数中,将进行一系列的初始化,例如初始化监听套接字,初始化已连接套接字,初始化io_service,初始化信号signal等等。

    server::server(const std::string& address, const std::string& port,
        const std::string& doc_root)
        : io_service_(),
        signals_(io_service_),
        acceptor_(io_service_),
        connection_manager_(),
        socket_(io_service_),
        request_handler_(doc_root)//处理请求的类
    {
        // Register to handle the signals that indicate when the server should exit.
        // It is safe to register for the same signal multiple times in a program,
        // provided all registration for the specified signal is made through Asio.
        signals_.add(SIGINT);
        signals_.add(SIGTERM);
#if defined(SIGQUIT)
        signals_.add(SIGQUIT);
#endif // defined(SIGQUIT)

        do_await_stop();

        // Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR).
        boost::asio::ip::tcp::resolver resolver(io_service_);
        boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve({addres

你可能感兴趣的:(boost.asio学习,boost-asio,网络编程,http)