http_server.cpp
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, boost::asio::ip::resolver_query_base::flags());
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 HttpServer::~HttpServer() {
00022   stop();
00023 }
00024 
00025 void HttpServer::run()
00026 {
00027   start_accept();
00028   for (std::size_t i = 0; i < thread_pool_size_; ++i)
00029   {
00030     boost::shared_ptr<boost::thread> thread(new boost::thread(
00031         boost::bind(&boost::asio::io_service::run, &io_service_)));
00032     threads_.push_back(thread);
00033   }
00034 }
00035 
00036 void HttpServer::start_accept()
00037 {
00038   new_connection_.reset(new HttpConnection(io_service_, request_handler_));
00039   acceptor_.async_accept(new_connection_->socket(),
00040                          boost::bind(&HttpServer::handle_accept, this,
00041                                      boost::asio::placeholders::error));
00042 }
00043 
00044 void HttpServer::handle_accept(const boost::system::error_code &e)
00045 {
00046   if (!e)
00047   {
00048     new_connection_->start();
00049   }
00050   start_accept();
00051 }
00052 
00053 void HttpServer::stop()
00054 {
00055   if(acceptor_.is_open()) {
00056     acceptor_.cancel();
00057     acceptor_.close();
00058   }
00059   io_service_.stop();
00060   // Wait for all threads in the pool to exit.
00061   for (std::size_t i = 0; i < threads_.size(); ++i)
00062     threads_[i]->join();
00063   threads_.clear();
00064 }
00065 
00066 }


async_web_server_cpp
Author(s): Mitchell Wills
autogenerated on Fri Mar 4 2016 11:30:14