我从网上搜索并尝试实施它
这是我的代码:
MulticastSender.h
// Standard includes.
#include <iostream>
#include <string>
#include <vector>
#include <set>
// 3rd party includes.
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
class MulticastSender
{
public:
typedef std::set<boost::asio::ip::udp::endpoint>::iterator distinationListIT;
MulticastSender(const std::string& ip, const unsigned short& port);
~MulticastSender();
void AddGroup(const std::string& ip);
void LeaveGroup(const std::string& ip);
void Send(const std::string& data);
private:
std::set<boost::asio::ip::udp::endpoint> m_destinationList;
boost::asio::ip::udp::socket* m_socket;
boost::asio::io_service m_service;
unsigned short m_port;
};
MulticastSender.cpp
#include "stdafx.h"
#include "MulticastSender.h"
MulticastSender::MulticastSender(const std::string& ip, const unsigned short& port)
{
boost::asio::ip::address address = boost::asio::ip::address::from_string(ip);
boost::asio::ip::udp::endpoint destination(address, port);
m_destinationList.insert(destination);
// Create socket.
m_socket = new boost::asio::ip::udp::socket(m_service);
m_socket->open(boost::asio::ip::udp::v4());
// Allow other processes to reuse the address, permitting other processes on
// the same machine to use the multicast address.
m_socket->set_option(boost::asio::ip::udp::socket::reuse_address(true));
// Guarantee the loopback is enabled so that multiple processes on the same
// machine can receive data that originates from the same socket.
m_socket->set_option(boost::asio::ip::multicast::enable_loopback(true));
m_socket->bind(boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4::any(), port));
m_service.run();
// Join group.
m_socket->set_option(boost::asio::ip::multicast::join_group(address));
}
MulticastSender::~MulticastSender()
{
}
void MulticastSender::AddGroup(const std::string& ip)
{
boost::asio::ip::address address = boost::asio::ip::address::from_string(ip);
// Join group.
m_socket->set_option(boost::asio::ip::multicast::join_group(address));
boost::asio::ip::udp::endpoint destination(address, m_port);
m_destinationList.insert(destination);
}
void MulticastSender::LeaveGroup(const std::string& ip)
{
boost::asio::ip::address address = boost::asio::ip::address::from_string(ip);
// Leave group
m_socket->set_option(boost::asio::ip::multicast::leave_group(address));
boost::asio::ip::udp::endpoint destination(address, m_port);
m_destinationList.erase(destination);
}
void MulticastSender::Send(const std::string& data)
{
for (distinationListIT it = m_destinationList.begin(); it != m_destinationList.end(); it++)
{
m_socket->send_to(boost::asio::buffer(data), *(it));
}
}
的main.cpp
MulticastSender_3 sender("239.255.0.1", 6000);
while (true)
{
sender.Send("Hello");
std::cout << "Hello\n";
Sleep(2000);
}
问题是我使用wireshark来捕获输出,但我发现程序使用目标ip 239.255.0.1和端口5001并发送一些无意义的消息。 6000港口没有使用。
我尝试了\libs\asio\example\cpp03\multicast
的示例代码,但问题是我无法添加组和离开组。任何人都知道如何使它有效?