blocking_udp_echo_server.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //
  2. // blocking_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. enum { max_length = 1024 };
  15. void server(boost::asio::io_context& io_context, unsigned short port)
  16. {
  17. udp::socket sock(io_context, udp::endpoint(udp::v4(), port));
  18. for (;;)
  19. {
  20. char data[max_length];
  21. udp::endpoint sender_endpoint;
  22. size_t length = sock.receive_from(
  23. boost::asio::buffer(data, max_length), sender_endpoint);
  24. sock.send_to(boost::asio::buffer(data, length), sender_endpoint);
  25. }
  26. }
  27. int main(int argc, char* argv[])
  28. {
  29. try
  30. {
  31. if (argc != 2)
  32. {
  33. std::cerr << "Usage: blocking_udp_echo_server <port>\n";
  34. return 1;
  35. }
  36. boost::asio::io_context io_context;
  37. using namespace std; // For atoi.
  38. server(io_context, atoi(argv[1]));
  39. }
  40. catch (std::exception& e)
  41. {
  42. std::cerr << "Exception: " << e.what() << "\n";
  43. }
  44. return 0;
  45. }