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