forked from boostorg/beast
Use timeouts in HTTP client examples
This commit is contained in:
@@ -16,8 +16,6 @@
|
||||
#include <boost/beast/core.hpp>
|
||||
#include <boost/beast/http.hpp>
|
||||
#include <boost/beast/version.hpp>
|
||||
#include <boost/asio/connect.hpp>
|
||||
#include <boost/asio/ip/tcp.hpp>
|
||||
#include <cstdlib>
|
||||
#include <functional>
|
||||
#include <iostream>
|
||||
@@ -31,6 +29,9 @@ using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// The type of stream to use
|
||||
using stream_type = beast::tcp_stream<net::io_context::executor_type>;
|
||||
|
||||
// Report a failure
|
||||
void
|
||||
fail(beast::error_code ec, char const* what)
|
||||
@@ -42,7 +43,7 @@ fail(beast::error_code ec, char const* what)
|
||||
class session : public std::enable_shared_from_this<session>
|
||||
{
|
||||
tcp::resolver resolver_;
|
||||
tcp::socket socket_;
|
||||
stream_type stream_;
|
||||
beast::flat_buffer buffer_; // (Must persist between reads)
|
||||
http::request<http::empty_body> req_;
|
||||
http::response<http::string_body> res_;
|
||||
@@ -52,7 +53,7 @@ public:
|
||||
explicit
|
||||
session(net::io_context& ioc)
|
||||
: resolver_(ioc)
|
||||
, socket_(ioc)
|
||||
, stream_(ioc)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -90,11 +91,13 @@ public:
|
||||
if(ec)
|
||||
return fail(ec, "resolve");
|
||||
|
||||
// Set a timeout on the operation
|
||||
stream_.expires_after(std::chrono::seconds(30));
|
||||
|
||||
// Make the connection on the IP address we get from a lookup
|
||||
net::async_connect(
|
||||
socket_,
|
||||
results.begin(),
|
||||
results.end(),
|
||||
beast::async_connect(
|
||||
stream_,
|
||||
results,
|
||||
std::bind(
|
||||
&session::on_connect,
|
||||
shared_from_this(),
|
||||
@@ -107,8 +110,11 @@ public:
|
||||
if(ec)
|
||||
return fail(ec, "connect");
|
||||
|
||||
// Set a timeout on the operation
|
||||
stream_.expires_after(std::chrono::seconds(30));
|
||||
|
||||
// Send the HTTP request to the remote host
|
||||
http::async_write(socket_, req_,
|
||||
http::async_write(stream_, req_,
|
||||
std::bind(
|
||||
&session::on_write,
|
||||
shared_from_this(),
|
||||
@@ -127,7 +133,7 @@ public:
|
||||
return fail(ec, "write");
|
||||
|
||||
// Receive the HTTP response
|
||||
http::async_read(socket_, buffer_, res_,
|
||||
http::async_read(stream_, buffer_, res_,
|
||||
std::bind(
|
||||
&session::on_read,
|
||||
shared_from_this(),
|
||||
@@ -149,7 +155,7 @@ public:
|
||||
std::cout << res_ << std::endl;
|
||||
|
||||
// Gracefully close the socket
|
||||
socket_.shutdown(tcp::socket::shutdown_both, ec);
|
||||
stream_.socket().shutdown(tcp::socket::shutdown_both, ec);
|
||||
|
||||
// not_connected happens sometimes so don't bother reporting it.
|
||||
if(ec && ec != beast::errc::not_connected)
|
||||
|
||||
Reference in New Issue
Block a user