client.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //
  2. // 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 <iostream>
  11. #include <boost/array.hpp>
  12. #include <boost/asio.hpp>
  13. using boost::asio::ip::udp;
  14. int main(int argc, char* argv[])
  15. {
  16. try
  17. {
  18. if (argc != 2)
  19. {
  20. std::cerr << "Usage: client <host>" << std::endl;
  21. return 1;
  22. }
  23. boost::asio::io_context io_context;
  24. udp::resolver resolver(io_context);
  25. udp::endpoint receiver_endpoint =
  26. *resolver.resolve(udp::v4(), argv[1], "daytime").begin();
  27. udp::socket socket(io_context);
  28. socket.open(udp::v4());
  29. boost::array<char, 1> send_buf = {{ 0 }};
  30. socket.send_to(boost::asio::buffer(send_buf), receiver_endpoint);
  31. boost::array<char, 128> recv_buf;
  32. udp::endpoint sender_endpoint;
  33. size_t len = socket.receive_from(
  34. boost::asio::buffer(recv_buf), sender_endpoint);
  35. std::cout.write(recv_buf.data(), len);
  36. }
  37. catch (std::exception& e)
  38. {
  39. std::cerr << e.what() << std::endl;
  40. }
  41. return 0;
  42. }