forked from boostorg/beast
Use timeouts in HTTP client examples
This commit is contained in:
@@ -18,10 +18,7 @@
|
||||
#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 <boost/asio/ssl/error.hpp>
|
||||
#include <boost/asio/ssl/stream.hpp>
|
||||
#include <boost/beast/_experimental/core/ssl_stream.hpp>
|
||||
#include <cstdlib>
|
||||
#include <functional>
|
||||
#include <iostream>
|
||||
@@ -36,6 +33,10 @@ using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// The type of stream to use
|
||||
using stream_type =
|
||||
beast::ssl_stream<beast::tcp_stream<net::io_context::executor_type>>;
|
||||
|
||||
// Report a failure
|
||||
void
|
||||
fail(beast::error_code ec, char const* what)
|
||||
@@ -47,7 +48,7 @@ fail(beast::error_code ec, char const* what)
|
||||
class session : public std::enable_shared_from_this<session>
|
||||
{
|
||||
tcp::resolver resolver_;
|
||||
ssl::stream<tcp::socket> stream_;
|
||||
stream_type stream_;
|
||||
beast::flat_buffer buffer_; // (Must persist between reads)
|
||||
http::request<http::empty_body> req_;
|
||||
http::response<http::string_body> res_;
|
||||
@@ -103,11 +104,13 @@ public:
|
||||
if(ec)
|
||||
return fail(ec, "resolve");
|
||||
|
||||
// Set a timeout on the operation
|
||||
beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30));
|
||||
|
||||
// Make the connection on the IP address we get from a lookup
|
||||
net::async_connect(
|
||||
stream_.next_layer(),
|
||||
results.begin(),
|
||||
results.end(),
|
||||
beast::async_connect(
|
||||
beast::get_lowest_layer(stream_),
|
||||
results,
|
||||
std::bind(
|
||||
&session::on_connect,
|
||||
shared_from_this(),
|
||||
@@ -135,6 +138,9 @@ public:
|
||||
if(ec)
|
||||
return fail(ec, "handshake");
|
||||
|
||||
// Set a timeout on the operation
|
||||
beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30));
|
||||
|
||||
// Send the HTTP request to the remote host
|
||||
http::async_write(stream_, req_,
|
||||
std::bind(
|
||||
@@ -176,6 +182,9 @@ public:
|
||||
// Write the message to standard out
|
||||
std::cout << res_ << std::endl;
|
||||
|
||||
// Set a timeout on the operation
|
||||
beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30));
|
||||
|
||||
// Gracefully close the stream
|
||||
stream_.async_shutdown(
|
||||
std::bind(
|
||||
|
||||
Reference in New Issue
Block a user