server.cc 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // server.cc
  3. // ~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2010 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. #include <boost/bind.hpp>
  11. #include "Experimental/http_server/server.h"
  12. namespace http_server {
  13. server::server(const std::string& address, const std::string& port,
  14. const std::string& doc_root) :
  15. io_service_(), acceptor_(io_service_), connection_manager_(),
  16. new_connection_(new connection(io_service_, connection_manager_,
  17. request_handler_)), request_handler_(doc_root)
  18. {
  19. // Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR).
  20. boost::asio::ip::tcp::resolver resolver(io_service_);
  21. boost::asio::ip::tcp::resolver::query query(address, port);
  22. boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query);
  23. acceptor_.open(endpoint.protocol());
  24. acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
  25. acceptor_.bind(endpoint);
  26. acceptor_.listen();
  27. acceptor_.async_accept(new_connection_->socket(), boost::bind(
  28. &server::handle_accept, this, boost::asio::placeholders::error));
  29. }
  30. void server::run()
  31. {
  32. // The io_service::run() call will block until all asynchronous operations
  33. // have finished. While the server is running, there is always at least one
  34. // asynchronous operation outstanding: the asynchronous accept call waiting
  35. // for new incoming connections.
  36. io_service_.run();
  37. }
  38. void server::stop()
  39. {
  40. // Post a call to the stop function so that server::stop() is safe to call
  41. // from any thread.
  42. io_service_.post(boost::bind(&server::handle_stop, this));
  43. }
  44. void server::handle_accept(const boost::system::error_code& e)
  45. {
  46. if (!e)
  47. {
  48. connection_manager_.start(new_connection_);
  49. new_connection_.reset(new connection(io_service_, connection_manager_,
  50. request_handler_));
  51. acceptor_.async_accept(new_connection_->socket(), boost::bind(
  52. &server::handle_accept, this, boost::asio::placeholders::error));
  53. }
  54. }
  55. void server::handle_stop()
  56. {
  57. // The server is stopped by cancelling all outstanding asynchronous
  58. // operations. Once all operations have finished the io_service::run() call
  59. // will exit.
  60. acceptor_.close();
  61. connection_manager_.stop_all();
  62. }
  63. } // namespace http_server