receiver.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. //
  2. // receiver.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 <array>
  11. #include <iostream>
  12. #include <string>
  13. #include <boost/asio.hpp>
  14. constexpr short multicast_port = 30001;
  15. class receiver
  16. {
  17. public:
  18. receiver(boost::asio::io_context& io_context,
  19. const boost::asio::ip::address& listen_address,
  20. const boost::asio::ip::address& multicast_address)
  21. : socket_(io_context)
  22. {
  23. // Create the socket so that multiple may be bound to the same address.
  24. boost::asio::ip::udp::endpoint listen_endpoint(
  25. listen_address, multicast_port);
  26. socket_.open(listen_endpoint.protocol());
  27. socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));
  28. socket_.bind(listen_endpoint);
  29. // Join the multicast group.
  30. socket_.set_option(
  31. boost::asio::ip::multicast::join_group(multicast_address));
  32. do_receive();
  33. }
  34. private:
  35. void do_receive()
  36. {
  37. socket_.async_receive_from(
  38. boost::asio::buffer(data_), sender_endpoint_,
  39. [this](boost::system::error_code ec, std::size_t length)
  40. {
  41. if (!ec)
  42. {
  43. std::cout.write(data_.data(), length);
  44. std::cout << std::endl;
  45. do_receive();
  46. }
  47. });
  48. }
  49. boost::asio::ip::udp::socket socket_;
  50. boost::asio::ip::udp::endpoint sender_endpoint_;
  51. std::array<char, 1024> data_;
  52. };
  53. int main(int argc, char* argv[])
  54. {
  55. try
  56. {
  57. if (argc != 3)
  58. {
  59. std::cerr << "Usage: receiver <listen_address> <multicast_address>\n";
  60. std::cerr << " For IPv4, try:\n";
  61. std::cerr << " receiver 0.0.0.0 239.255.0.1\n";
  62. std::cerr << " For IPv6, try:\n";
  63. std::cerr << " receiver 0::0 ff31::8000:1234\n";
  64. return 1;
  65. }
  66. boost::asio::io_context io_context;
  67. receiver r(io_context,
  68. boost::asio::ip::make_address(argv[1]),
  69. boost::asio::ip::make_address(argv[2]));
  70. io_context.run();
  71. }
  72. catch (std::exception& e)
  73. {
  74. std::cerr << "Exception: " << e.what() << "\n";
  75. }
  76. return 0;
  77. }