Imported Upstream version 1.57.0
[platform/upstream/boost.git] / doc / html / boost_asio / example / cpp11 / echo / blocking_udp_echo_client.cpp
1 //
2 // blocking_udp_echo_client.cpp
3 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4 //
5 // Copyright (c) 2003-2014 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::udp;
17
18 enum { max_length = 1024 };
19
20 int main(int argc, char* argv[])
21 {
22   try
23   {
24     if (argc != 3)
25     {
26       std::cerr << "Usage: blocking_udp_echo_client <host> <port>\n";
27       return 1;
28     }
29
30     boost::asio::io_service io_service;
31
32     udp::socket s(io_service, udp::endpoint(udp::v4(), 0));
33
34     udp::resolver resolver(io_service);
35     udp::endpoint endpoint = *resolver.resolve({udp::v4(), argv[1], argv[2]});
36
37     std::cout << "Enter message: ";
38     char request[max_length];
39     std::cin.getline(request, max_length);
40     size_t request_length = std::strlen(request);
41     s.send_to(boost::asio::buffer(request, request_length), endpoint);
42
43     char reply[max_length];
44     udp::endpoint sender_endpoint;
45     size_t reply_length = s.receive_from(
46         boost::asio::buffer(reply, max_length), sender_endpoint);
47     std::cout << "Reply is: ";
48     std::cout.write(reply, reply_length);
49     std::cout << "\n";
50   }
51   catch (std::exception& e)
52   {
53     std::cerr << "Exception: " << e.what() << "\n";
54   }
55
56   return 0;
57 }