Use timeouts in HTTP server examples

This commit is contained in:
Vinnie Falco
2019-02-10 11:42:01 -08:00
parent 9b14774ada
commit 5b97fbb966
8 changed files with 225 additions and 251 deletions
@@ -16,9 +16,7 @@
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/bind_executor.hpp>
#include <boost/asio/coroutine.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/strand.hpp>
#include <boost/config.hpp>
#include <algorithm>
@@ -207,6 +205,9 @@ handle_request(
//------------------------------------------------------------------------------
// The type of stream to use
using stream_type = beast::tcp_stream<net::io_context::strand>;
// Report a failure
void
fail(beast::error_code ec, char const* what)
@@ -248,22 +249,18 @@ class session
// Write the response
http::async_write(
self_.socket_,
self_.stream_,
*sp,
net::bind_executor(
self_.strand_,
std::bind(
&session::loop,
self_.shared_from_this(),
std::placeholders::_1,
std::placeholders::_2,
sp->need_eof())));
std::bind(
&session::loop,
self_.shared_from_this(),
std::placeholders::_1,
std::placeholders::_2,
sp->need_eof()));
}
};
tcp::socket socket_;
net::strand<
net::io_context::executor_type> strand_;
stream_type stream_;
beast::flat_buffer buffer_;
std::shared_ptr<std::string const> doc_root_;
http::request<http::string_body> req_;
@@ -276,8 +273,7 @@ public:
session(
tcp::socket socket,
std::shared_ptr<std::string const> const& doc_root)
: socket_(std::move(socket))
, strand_(socket_.get_executor())
: stream_(std::move(socket))
, doc_root_(doc_root)
, lambda_(*this)
{
@@ -306,16 +302,17 @@ public:
// otherwise the operation behavior is undefined.
req_ = {};
// Set the timeout.
stream_.expires_after(std::chrono::seconds(30));
// Read a request
yield http::async_read(socket_, buffer_, req_,
net::bind_executor(
strand_,
std::bind(
&session::loop,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2,
false)));
yield http::async_read(stream_, buffer_, req_,
std::bind(
&session::loop,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2,
false));
if(ec == http::error::end_of_stream)
{
// The remote host closed the connection
@@ -340,7 +337,7 @@ public:
}
// Send a TCP shutdown
socket_.shutdown(tcp::socket::shutdown_send, ec);
stream_.socket().shutdown(tcp::socket::shutdown_send, ec);
// At this point the connection is closed gracefully
}