0

I'm using boost::beast in order to establish client based http session and send/receive messages.

My connection is defined as a class member so as long as it wasn't disconnected by the peer, I can re-use it.

class myClass {
      boost::beast::ssl_stream<boost::beast::tcp_stream> stream_;
}

Here is how I connect to server when myClass c'tor is being called.

get_lowest_layer(stream_).async_connect(results, yield[ec_]);

stream_.async_handshake(boost::asio::ssl::stream_base::client, yield[ec_]);

boost::beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30));

and this is how I send my on-demand messages :

  http::request<http::string_body> req(http::verb::post, myPostUri, 12);
  req.set(boost::beast::http::field::content_length,
          std::to_string(someJsonText.length()));
  req.set(boost::beast::http::field::body, someJsonText);
  req.set(boost::beast::http::field::content_type, "application/json");
  req.prepare_payload();
  http::write(stream_, req);

  boost::beast::flat_buffer buffer;
  http::response<boost::beast::http::dynamic_body> res;
  http::read(stream_, buffer, res);

I'd like to add some exception handler in order to tackle the following scenarios :

  1. the server is offline when client tried to connect. So it should retry re-connecting until the server gets back online.

  2. the server reset connection (connection reset by peer). This happens due to connection was unused for a period of time. so I'd like to make a retry and get the connection back.

Currently when one of these scenarios happens, I get the following exception

libc++abi: terminating with uncaught exception of type 
boost::wrapexcept<boost::system::system_error>: end of stream

terminating with uncaught exception of type 
boost::wrapexcept<boost::system::system_error>: end of stream

So I know what to do in general but I'm not sure how. should I just try to re-connect or also perform the other steps in the initialization flow (ssl handshake)

Perhaps anybody can show me how to do it right ?

Zohar81
  • 3,904
  • 4
  • 23
  • 63
  • See e.g. https://stackoverflow.com/questions/69896335/how-do-i-make-this-https-connection-persistent-in-beast/69908177#69908177 - which is a bit wider in scope but does address exactly the reconnect questions – sehe Dec 04 '21 at 13:27

0 Answers0