使用boost::asio在同一主机上发送多播消息

Multicast message on same host using boost::asio

本文关键字:多播 消息 主机 boost asio 使用      更新时间:2023-10-16

我正在实现发送方/接收方应用程序,以便在同一主机上进行多播对话。

在构造函数中,我使用以下代码来设置套接字。

boost::asio::ip::udp::endpoint listenEndpoint(listenAddr, mcastPort);
m_socket.open(listenEndpoint.protocol());
m_socket.set_option(boost::asio::ip::udp::socket::reuse_address(true));
m_socket.set_option(boost::asio::ip::multicast::enable_loopback(true));
m_socket.set_option(boost::asio::ip::multicast::hops(1));
m_socket.bind(listenEndpoint);
// Join the multicast group
m_socket.set_option(boost::asio::ip::multicast::join_group(mcastAddr));
m_socket.async_receive_from(boost::asio::buffer(m_data, MAX_PTP_MSG_LENGTH),
        m_senderEndpoint, boost::bind(&PtpIpc::HandleReceiveFrom, this, 
        boost::asio::placeholders::error,
        boost::asio::placeholders::bytes_transferred));

其中listenAddr为0.0.0.0。

我的发送方法代码如下:

m_socket.async_send_to(boost::asio::buffer(data, size), m_remoteEndpoint,
    boost::bind(&PtpIpc::HandleSendTo, this,
    boost::asio::placeholders::error,
    boost::asio::placeholders::bytes_transferred));

其中m_remoteEndpoint为组播地址224.0.1.129和组播端口320。

应用程序A似乎没有从应用程序B接收多播消息,反之亦然,当两者都在同一主机上时。但是如果我将应用程序B移动到同一子网上的另一台机器上……然后,应用程序A听到多播消息并回复给应用程序B,应用程序B也可以接收到应用程序A的回复消息。我启用了环回,并设置了套接字reuse_address选项。我错过了什么?

当您删除环回选项时会发生什么。我有一个类似的问题,并删除修复它。