Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

Daytime.10 - An asynchronous TCP daytime client using as_tuple

In this tutorial we will change the client from tutorial Daytime.9 to use the boost::asio::as_tuple completion token adapter, so that the end of the response is detected without an exception. This tutorial program requires a compiler that supports C++20 coroutines.

#include <array>
#include <exception>
#include <iostream>
#include <string>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

The beginning of the get_daytime() coroutine is unchanged from tutorial Daytime.9. A failure to resolve the server name or to connect to the server is still thrown as an exception.

boost::asio::awaitable<void> get_daytime(std::string host)
{
  auto executor = co_await boost::asio::this_coro::executor;

  tcp::resolver resolver(executor);
  tcp::resolver::results_type endpoints =
    co_await resolver.async_resolve(host, "daytime");

  tcp::socket socket(executor);
  co_await boost::asio::async_connect(socket, endpoints,
      boost::asio::cancel_after(boost::asio::chrono::seconds(10)));

The read loop no longer needs a try block.

  for (;;)
  {
    std::array<char, 128> buf;

    auto [error, len] = co_await socket.async_read_some(boost::asio::buffer(buf),
        boost::asio::as_tuple(boost::asio::cancel_after(boost::asio::chrono::seconds(10))));

The boost::asio::as_tuple adapter packages the results of the operation into a single std::tuple, and an error is no longer thrown as an exception. The ip::tcp::socket::async_read_some() operation completes with an error code and the number of bytes transferred, so the co_await expression produces a tuple of a boost::system::error_code and a std::size_t. We unpack these using a structured binding.

In this program boost::asio::as_tuple wraps boost::asio::cancel_after, which in turn wraps the operation's default completion token. A read that times out produces the boost::asio::error::operation_aborted error, and this is delivered in the tuple. Using the pipe operator, the same operation could be written as:

auto [error, len] = co_await (socket.async_read_some(boost::asio::buffer(buf))
    | boost::asio::cancel_after(boost::asio::chrono::seconds(10)) | boost::asio::as_tuple);

The error is now tested in the same way as in tutorial Daytime.1. When the server closes the connection, the read completes with the boost::asio::error::eof error and we leave the loop. Any other error, including a timeout, is thrown as an exception.

    if (error == boost::asio::error::eof)
      break; // Connection closed cleanly by peer.
    else if (error)
      throw boost::system::system_error(error); // Some other error.

    std::cout.write(buf.data(), len);
  }
}

The main function is unchanged from tutorial Daytime.9.

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 2)
    {
      std::cerr << "Usage: client <host>" << std::endl;
      return 1;
    }

    boost::asio::io_context io_context;

    boost::asio::co_spawn(io_context, get_daytime(argv[1]),
        [](std::exception_ptr e)
        {
          if (e)
            std::rethrow_exception(e);
        });

    io_context.run();
  }
  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}

See the full source listing

Return to the tutorial index

Previous: Daytime.9 - An asynchronous TCP daytime client with timeouts


PrevUpHomeNext