| Home | Libraries | People | FAQ | More

# http/server/server.cpp

Go to the documentation of this file.

    00001 #include "server.hpp"
    00002 #include <boost/bind.hpp>
    00003
    00004 namespace http {
    00005 namespace server {
    00006
    00007 server::server(const std::string& address, const std::string& port,
    00008     const std::string& doc_root)
    00009   : io_service_(),
    00010     acceptor_(io_service_),
    00011     connection_manager_(),
    00012     new_connection_(new connection(io_service_,
    00013           connection_manager_, request_handler_)),
    00014     request_handler_(doc_root)
    00015 {
    00016   // Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR).
    00017   boost::asio::ip::tcp::resolver resolver(io_service_);
    00018   boost::asio::ip::tcp::resolver::query query(address, port);
    00019   boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query);
    00020   acceptor_.open(endpoint.protocol());
    00021   acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
    00022   acceptor_.bind(endpoint);
    00023   acceptor_.listen();
    00024   acceptor_.async_accept(new_connection_->socket(),
    00025       boost::bind(&server::handle_accept, this,
    00026         boost::asio::placeholders::error));
    00027 }
    00028
    00029 void server::run()
    00030 {
    00031   // The io_service::run() call will block until all asynchronous operations
    00032   // have finished. While the server is running, there is always at least one
    00033   // asynchronous operation outstanding: the asynchronous accept call waiting
    00034   // for new incoming connections.
    00035   io_service_.run();
    00036 }
    00037
    00038 void server::stop()
    00039 {
    00040   // Post a call to the stop function so that server::stop() is safe to call
    00041   // from any thread.
    00042   io_service_.post(boost::bind(&server::handle_stop, this));
    00043 }
    00044
    00045 void server::handle_accept(const boost::asio::error& e)
    00046 {
    00047   if (!e)
    00048   {
    00049     connection_manager_.start(new_connection_);
    00050     new_connection_.reset(new connection(io_service_,
    00051           connection_manager_, request_handler_));
    00052     acceptor_.async_accept(new_connection_->socket(),
    00053         boost::bind(&server::handle_accept, this,
    00054           boost::asio::placeholders::error));
    00055   }
    00056 }
    00057
    00058 void server::handle_stop()
    00059 {
    00060   // The server is stopped by cancelling all outstanding asynchronous
    00061   // operations. Once all operations have finished the io_service::run() call
    00062   // will exit.
    00063   acceptor_.close();
    00064   connection_manager_.stop_all();
    00065 }
    00066
    00067 } // namespace server
    00068 } // namespace http

| Copyright © 2003 - 2006 Christopher M. Kohlhoff