Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

Source listing for Daytime.9

//
// client.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2026 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

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

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

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)));

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

      size_t len = co_await socket.async_read_some(boost::asio::buffer(buf),
          boost::asio::cancel_after(boost::asio::chrono::seconds(10)));

      std::cout.write(buf.data(), len);
    }
  }
  catch (boost::system::system_error& e)
  {
    if (e.code() != boost::asio::error::eof)
      throw; // Some other error.
  }
}

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;
}

Return to Daytime.9 - An asynchronous TCP daytime client with timeouts


PrevUpHomeNext