官网上的例子在这里https://www.boost.org/doc/libs/1_67_0/doc/html/boost_asio/examples/cpp03_examples.html
一 http::server 只有一个主线程
首先http::server是一个简单的单线程服务器,只有一个主线程;
httpserver的思想比较简单:主线程先预先申请一个连接对象connection并使用的acceptor对connection对象监听客户端的连接,连接到来后将该连接加入到连接管理connection_manager数组中,并重新预分配一个连接对象开始新一轮监听;
connection_manager调用connection的start()函数,开始向io_context投递接收请求,接收请求处理完后调用回调函数handle_read进行处理,并开始新一轮投递接收请求;
里面比较重要的文件是
server.hpp server.cpp
connection.hpp connection.cpp
connection_manager.hpp connection_manager.cpp
main.cpp
其他文件在这三个server中是一样的,用于处理接收和回复,这里不予讨论。
connection作用:处理接收,发送请求
connection.hpp源码如下:
1 // 2 // connection.hpp 3 // ~~~~~~~~~~~~~~ 4 // 5 // Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) 6 // 7 // Distributed under the Boost Software License, Version 1.0. (See accompanying 8 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) 9 // 10 11 #ifndef HTTP_CONNECTION_HPP 12 #define HTTP_CONNECTION_HPP 13 14 #include <boost/asio.hpp> 15 #include <boost/array.hpp> 16 #include <boost/noncopyable.hpp> 17 #include <boost/shared_ptr.hpp> 18 #include <boost/enable_shared_from_this.hpp> 19 #include "reply.hpp" 20 #include "request.hpp" 21 #include "request_handler.hpp" 22 #include "request_parser.hpp" 23 24 namespace http { 25 namespace server { 26 27 class connection_manager; 28 29 /// Represents a single connection from a client. 30 class connection 31 : public boost::enable_shared_from_this<connection>, 32 private boost::noncopyable 33 { 34 public: 35 /// Construct a connection with the given io_context. 36 explicit connection(boost::asio::io_context& io_context, 37 connection_manager& manager, request_handler& handler); 38 39 /// Get the socket associated with the connection. 40 boost::asio::ip::tcp::socket& socket(); 41 42 /// Start the first asynchronous operation for the connection. 43 void start(); 44 45 /// Stop all asynchronous operations associated with the connection. 46 void stop(); 47 48 private: 49 /// Handle completion of a read operation. 50 void handle_read(const boost::system::error_code& e, 51 std::size_t bytes_transferred); 52 53 /// Handle completion of a write operation. 54 void handle_write(const boost::system::error_code& e); 55 56 /// Socket for the connection. 57 boost::asio::ip::tcp::socket socket_; 58 59 /// The manager for this connection. 60 connection_manager& connection_manager_; 61 62 /// The handler used to process the incoming request. 63 request_handler& request_handler_; 64 65 /// Buffer for incoming data. 66 boost::array<char, 8192> buffer_; 67 68 /// The incoming request. 69 request request_; 70 71 /// The parser for the incoming request. 72 request_parser request_parser_; 73 74 /// The reply to be sent back to the client. 75 reply reply_; 76 }; 77 78 typedef boost::shared_ptr<connection> connection_ptr; 79 80 } // namespace server 81 } // namespace http 82 83 #endif // HTTP_CONNECTION_HPP