5 // Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com)
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)
11 #include "connection.hpp"
13 #include <boost/bind.hpp>
14 #include "connection_manager.hpp"
15 #include "request_handler.hpp"
20 connection::connection(boost::asio::io_service& io_service,
21 connection_manager& manager, request_handler& handler)
22 : socket_(io_service),
23 connection_manager_(manager),
24 request_handler_(handler)
28 boost::asio::ip::tcp::socket& connection::socket()
33 void connection::start()
35 socket_.async_read_some(boost::asio::buffer(buffer_),
36 boost::bind(&connection::handle_read, shared_from_this(),
37 boost::asio::placeholders::error,
38 boost::asio::placeholders::bytes_transferred));
41 void connection::stop()
46 void connection::handle_read(const boost::system::error_code& e,
47 std::size_t bytes_transferred)
51 boost::tribool result;
52 boost::tie(result, boost::tuples::ignore) = request_parser_.parse(
53 request_, buffer_.data(), buffer_.data() + bytes_transferred);
57 request_handler_.handle_request(request_, reply_);
58 boost::asio::async_write(socket_, reply_.to_buffers(),
59 boost::bind(&connection::handle_write, shared_from_this(),
60 boost::asio::placeholders::error));
64 reply_ = reply::stock_reply(reply::bad_request);
65 boost::asio::async_write(socket_, reply_.to_buffers(),
66 boost::bind(&connection::handle_write, shared_from_this(),
67 boost::asio::placeholders::error));
71 socket_.async_read_some(boost::asio::buffer(buffer_),
72 boost::bind(&connection::handle_read, shared_from_this(),
73 boost::asio::placeholders::error,
74 boost::asio::placeholders::bytes_transferred));
77 else if (e != boost::asio::error::operation_aborted)
79 connection_manager_.stop(shared_from_this());
83 void connection::handle_write(const boost::system::error_code& e)
87 // Initiate graceful connection closure.
88 boost::system::error_code ignored_ec;
89 socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec);
92 if (e != boost::asio::error::operation_aborted)
94 connection_manager_.stop(shared_from_this());