Go to the documentation of this file.00001 #include "async_web_server_cpp/http_server.hpp"
00002 #include "async_web_server_cpp/http_reply.hpp"
00003
00004 namespace async_web_server_cpp
00005 {
00006
00007 HttpServer::HttpServer(const std::string &address, const std::string &port,
00008 HttpServerRequestHandler request_handler, std::size_t thread_pool_size)
00009 : acceptor_(io_service_), thread_pool_size_(thread_pool_size), request_handler_(request_handler)
00010 {
00011
00012 boost::asio::ip::tcp::resolver resolver(io_service_);
00013 boost::asio::ip::tcp::resolver::query query(address, port);
00014 boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query);
00015 acceptor_.open(endpoint.protocol());
00016 acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
00017 acceptor_.bind(endpoint);
00018 acceptor_.listen();
00019 }
00020
00021
00022 void HttpServer::run()
00023 {
00024 start_accept();
00025 for (std::size_t i = 0; i < thread_pool_size_; ++i)
00026 {
00027 boost::shared_ptr<boost::thread> thread(new boost::thread(
00028 boost::bind(&boost::asio::io_service::run, &io_service_)));
00029 threads_.push_back(thread);
00030 }
00031 }
00032
00033 void HttpServer::start_accept()
00034 {
00035 new_connection_.reset(new HttpConnection(io_service_, request_handler_));
00036 acceptor_.async_accept(new_connection_->socket(),
00037 boost::bind(&HttpServer::handle_accept, this,
00038 boost::asio::placeholders::error));
00039 }
00040
00041 void HttpServer::handle_accept(const boost::system::error_code &e)
00042 {
00043 if (!e)
00044 {
00045 new_connection_->start();
00046 }
00047 start_accept();
00048 }
00049
00050 void HttpServer::stop()
00051 {
00052 acceptor_.cancel();
00053 acceptor_.close();
00054 io_service_.stop();
00055
00056 for (std::size_t i = 0; i < threads_.size(); ++i)
00057 threads_[i]->join();
00058 }
00059
00060 }