简体   繁体   中英

How can i implement simple boost.asio mulsticast sender?

I want to use boost.asio to create a multicast UDP sender. I have a my thread and I want to use boost only for:

  • socket;

  • send();

  • Error Handling;

Can you suggest something?

This is relatively simple to accomplish. Here's a basic class that handles most of everything you need using synchronous calls:

#include <boost/asio.hpp>
#include <boost/scoped_ptr.hpp>

class MulticastSender
{
public:
   MulticastSender(const boost::asio::ip::address& multicast_addr,
      const unsigned short multicast_port)
         : ep_(multicast_addr, multicast_port)
   {
      socket_.reset(new boost::asio::ip::udp::socket(svc_, ep_.protocol()));
   }

   ~MulticastSender()
   {
      socket_.reset(NULL);
   }

public:
   void send_data(const std::string& msg)
   {
      socket_->send_to(
         boost::asio::buffer(msg.str()), ep_);
   }

private:
   boost::asio::ip::udp::endpoint                  ep_;
   boost::scoped_ptr<boost::asio::ip::udp::socket> socket_;
   boost::asio::io_service                         svc_;
};

This simple class meets 2 of your 3 requirements (no error handling). To use it, simply create an instance of it in an appropriate place, and your thread implementation just calls MulticastSender::send_data() to send the multicast data to the associated endpoint.

Did you give a try to the samples?

<boost>\libs\asio\example\multicast\

It contains sampples for

receiver.cpp
sender.cpp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM