• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // blocking_tcp_echo_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 <cstdlib>
12 #include <cstring>
13 #include <iostream>
14 #include <boost/asio.hpp>
15 
16 using boost::asio::ip::tcp;
17 
18 enum { max_length = 1024 };
19 
main(int argc,char * argv[])20 int main(int argc, char* argv[])
21 {
22   try
23   {
24     if (argc != 3)
25     {
26       std::cerr << "Usage: blocking_tcp_echo_client <host> <port>\n";
27       return 1;
28     }
29 
30     boost::asio::io_context io_context;
31 
32     tcp::resolver resolver(io_context);
33     tcp::resolver::results_type endpoints =
34       resolver.resolve(tcp::v4(), argv[1], argv[2]);
35 
36     tcp::socket s(io_context);
37     boost::asio::connect(s, endpoints);
38 
39     using namespace std; // For strlen.
40     std::cout << "Enter message: ";
41     char request[max_length];
42     std::cin.getline(request, max_length);
43     size_t request_length = strlen(request);
44     boost::asio::write(s, boost::asio::buffer(request, request_length));
45 
46     char reply[max_length];
47     size_t reply_length = boost::asio::read(s,
48         boost::asio::buffer(reply, request_length));
49     std::cout << "Reply is: ";
50     std::cout.write(reply, reply_length);
51     std::cout << "\n";
52   }
53   catch (std::exception& e)
54   {
55     std::cerr << "Exception: " << e.what() << "\n";
56   }
57 
58   return 0;
59 }
60