Ticket #13462: UdpMulticastSender_1_66.cpp

File UdpMulticastSender_1_66.cpp, 1.6 KB (added by nguyen.tnhoang@…, 5 years ago)

udp sender used to send sample messages to be listened to

Line 
1#define _CRT_SECURE_NO_WARNINGS
2#include <ctime>
3#include <iostream>
4#include <string>
5#include <boost/array.hpp>
6#include <boost/bind.hpp>
7#include <boost/shared_ptr.hpp>
8#include <boost/asio.hpp>
9#include <boost/lexical_cast.hpp>
10#include <boost/thread.hpp>
11using boost::asio::ip::udp;
12using std::cout;
13using std::cin;
14using std::endl;
15
16class sender
17{
18private:
19 boost::asio::ip::udp::endpoint endpoint_;
20 boost::asio::ip::udp::socket socket_;
21 boost::asio::steady_timer timer_;
22 int message_count_;
23 std::string message_;
24 short multicast_port = 13;
25 int max_message_count = 10;
26
27public:
28 sender(boost::asio::io_context& io_context, const boost::asio::ip::address& multicast_address)
29 : endpoint_(multicast_address, multicast_port),
30 socket_(io_context, endpoint_.protocol()),
31 timer_(io_context),
32 message_count_(0)
33 {
34 message_ = "abcd";
35 send_periodic();
36 }
37
38private:
39 void send_periodic()
40 {
41 static int i = 0;
42
43 std::ostringstream os;
44 os << "Message " << message_count_++;
45
46 socket_.async_send_to(boost::asio::buffer(message_), endpoint_, [this](boost::system::error_code ec, std::size_t /*length*/)
47 {
48 cout << i << endl; // show count
49 ++i;
50 });
51
52 timer_.expires_after(std::chrono::seconds(1));
53 timer_.async_wait([this](boost::system::error_code ec)
54 {
55 send_periodic();
56 });
57 }
58};
59
60int main(int argc, char* argv[])
61{
62 try
63 {
64 boost::asio::io_context io_context;
65 sender s(io_context, boost::asio::ip::make_address("127.0.0.1"));
66 io_context.run();
67 }
68 catch (std::exception& e)
69 {
70 std::cerr << "Exception: " << e.what() << "\n";
71 }
72
73 return 0;
74}