sender.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. //
  2. // sender.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 <sstream>
  12. #include <string>
  13. #include <boost/asio.hpp>
  14. #include "boost/bind.hpp"
  15. const short multicast_port = 30001;
  16. const int max_message_count = 10;
  17. class sender
  18. {
  19. public:
  20. sender(boost::asio::io_context& io_context,
  21. const boost::asio::ip::address& multicast_address)
  22. : endpoint_(multicast_address, multicast_port),
  23. socket_(io_context, endpoint_.protocol()),
  24. timer_(io_context),
  25. message_count_(0)
  26. {
  27. std::ostringstream os;
  28. os << "Message " << message_count_++;
  29. message_ = os.str();
  30. socket_.async_send_to(
  31. boost::asio::buffer(message_), endpoint_,
  32. boost::bind(&sender::handle_send_to, this,
  33. boost::asio::placeholders::error));
  34. }
  35. void handle_send_to(const boost::system::error_code& error)
  36. {
  37. if (!error && message_count_ < max_message_count)
  38. {
  39. timer_.expires_after(boost::asio::chrono::seconds(1));
  40. timer_.async_wait(
  41. boost::bind(&sender::handle_timeout, this,
  42. boost::asio::placeholders::error));
  43. }
  44. }
  45. void handle_timeout(const boost::system::error_code& error)
  46. {
  47. if (!error)
  48. {
  49. std::ostringstream os;
  50. os << "Message " << message_count_++;
  51. message_ = os.str();
  52. socket_.async_send_to(
  53. boost::asio::buffer(message_), endpoint_,
  54. boost::bind(&sender::handle_send_to, this,
  55. boost::asio::placeholders::error));
  56. }
  57. }
  58. private:
  59. boost::asio::ip::udp::endpoint endpoint_;
  60. boost::asio::ip::udp::socket socket_;
  61. boost::asio::steady_timer timer_;
  62. int message_count_;
  63. std::string message_;
  64. };
  65. int main(int argc, char* argv[])
  66. {
  67. try
  68. {
  69. if (argc != 2)
  70. {
  71. std::cerr << "Usage: sender <multicast_address>\n";
  72. std::cerr << " For IPv4, try:\n";
  73. std::cerr << " sender 239.255.0.1\n";
  74. std::cerr << " For IPv6, try:\n";
  75. std::cerr << " sender ff31::8000:1234\n";
  76. return 1;
  77. }
  78. boost::asio::io_context io_context;
  79. sender s(io_context, boost::asio::ip::make_address(argv[1]));
  80. io_context.run();
  81. }
  82. catch (std::exception& e)
  83. {
  84. std::cerr << "Exception: " << e.what() << "\n";
  85. }
  86. return 0;
  87. }