• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // client.cpp
3 // ~~~~~~~~~~
4 //
5 // Copyright (c) 2003-2021 Christopher M. Kohlhoff (chris at kohlhoff dot com)
6 //
7 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
9 //
10 
11 #include <iostream>
12 #include <boost/array.hpp>
13 #include <boost/asio.hpp>
14 
15 using boost::asio::ip::tcp;
16 
main(int argc,char * argv[])17 int main(int argc, char* argv[])
18 {
19   try
20   {
21     if (argc != 2)
22     {
23       std::cerr << "Usage: client <host>" << std::endl;
24       return 1;
25     }
26 
27     boost::asio::io_context io_context;
28 
29     tcp::resolver resolver(io_context);
30     tcp::resolver::results_type endpoints =
31       resolver.resolve(argv[1], "daytime");
32 
33     tcp::socket socket(io_context);
34     boost::asio::connect(socket, endpoints);
35 
36     for (;;)
37     {
38       boost::array<char, 128> buf;
39       boost::system::error_code error;
40 
41       size_t len = socket.read_some(boost::asio::buffer(buf), error);
42 
43       if (error == boost::asio::error::eof)
44         break; // Connection closed cleanly by peer.
45       else if (error)
46         throw boost::system::system_error(error); // Some other error.
47 
48       std::cout.write(buf.data(), len);
49     }
50   }
51   catch (std::exception& e)
52   {
53     std::cerr << e.what() << std::endl;
54   }
55 
56   return 0;
57 }
58