async_udp_echo_server.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. //
  2. // async_udp_echo_server.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 <iostream>
  12. #include <boost/asio.hpp>
  13. using boost::asio::ip::udp;
  14. class server
  15. {
  16. public:
  17. server(boost::asio::io_context& io_context, short port)
  18. : socket_(io_context, udp::endpoint(udp::v4(), port))
  19. {
  20. do_receive();
  21. }
  22. void do_receive()
  23. {
  24. socket_.async_receive_from(
  25. boost::asio::buffer(data_, max_length), sender_endpoint_,
  26. [this](boost::system::error_code ec, std::size_t bytes_recvd)
  27. {
  28. if (!ec && bytes_recvd > 0)
  29. {
  30. do_send(bytes_recvd);
  31. }
  32. else
  33. {
  34. do_receive();
  35. }
  36. });
  37. }
  38. void do_send(std::size_t length)
  39. {
  40. socket_.async_send_to(
  41. boost::asio::buffer(data_, length), sender_endpoint_,
  42. [this](boost::system::error_code /*ec*/, std::size_t /*bytes_sent*/)
  43. {
  44. do_receive();
  45. });
  46. }
  47. private:
  48. udp::socket socket_;
  49. udp::endpoint sender_endpoint_;
  50. enum { max_length = 1024 };
  51. char data_[max_length];
  52. };
  53. int main(int argc, char* argv[])
  54. {
  55. try
  56. {
  57. if (argc != 2)
  58. {
  59. std::cerr << "Usage: async_udp_echo_server <port>\n";
  60. return 1;
  61. }
  62. boost::asio::io_context io_context;
  63. server s(io_context, std::atoi(argv[1]));
  64. io_context.run();
  65. }
  66. catch (std::exception& e)
  67. {
  68. std::cerr << "Exception: " << e.what() << "\n";
  69. }
  70. return 0;
  71. }