9
3

server.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // 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 <ctime>
  11. #include <iostream>
  12. #include <string>
  13. #include <boost/array.hpp>
  14. #include <boost/asio.hpp>
  15. using boost::asio::ip::udp;
  16. std::string make_daytime_string()
  17. {
  18. using namespace std; // For time_t, time and ctime;
  19. time_t now = time(0);
  20. return ctime(&now);
  21. }
  22. int main()
  23. {
  24. try
  25. {
  26. boost::asio::io_context io_context;
  27. udp::socket socket(io_context, udp::endpoint(udp::v4(), 13));
  28. for (;;)
  29. {
  30. boost::array<char, 1> recv_buf;
  31. udp::endpoint remote_endpoint;
  32. boost::system::error_code error;
  33. socket.receive_from(boost::asio::buffer(recv_buf), remote_endpoint);
  34. std::string message = make_daytime_string();
  35. boost::system::error_code ignored_error;
  36. socket.send_to(boost::asio::buffer(message),
  37. remote_endpoint, 0, ignored_error);
  38. }
  39. }
  40. catch (std::exception& e)
  41. {
  42. std::cerr << e.what() << std::endl;
  43. }
  44. return 0;
  45. }