blocking_udp_echo_client.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //
  2. // blocking_udp_echo_client.cpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2019 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. #include <cstdlib>
  11. #include <cstring>
  12. #include <iostream>
  13. #include <boost/asio.hpp>
  14. using boost::asio::ip::udp;
  15. enum { max_length = 1024 };
  16. int main(int argc, char* argv[])
  17. {
  18. try
  19. {
  20. if (argc != 3)
  21. {
  22. std::cerr << "Usage: blocking_udp_echo_client <host> <port>\n";
  23. return 1;
  24. }
  25. boost::asio::io_context io_context;
  26. udp::socket s(io_context, udp::endpoint(udp::v4(), 0));
  27. udp::resolver resolver(io_context);
  28. udp::resolver::results_type endpoints =
  29. resolver.resolve(udp::v4(), argv[1], argv[2]);
  30. using namespace std; // For strlen.
  31. std::cout << "Enter message: ";
  32. char request[max_length];
  33. std::cin.getline(request, max_length);
  34. size_t request_length = strlen(request);
  35. s.send_to(boost::asio::buffer(request, request_length), *endpoints.begin());
  36. char reply[max_length];
  37. udp::endpoint sender_endpoint;
  38. size_t reply_length = s.receive_from(
  39. boost::asio::buffer(reply, max_length), sender_endpoint);
  40. std::cout << "Reply is: ";
  41. std::cout.write(reply, reply_length);
  42. std::cout << "\n";
  43. }
  44. catch (std::exception& e)
  45. {
  46. std::cerr << "Exception: " << e.what() << "\n";
  47. }
  48. return 0;
  49. }