我正在尝试使用Boost.Asio实现双向多播UDP通信。实际上我需要的是客户机-服务器架构。
我使用了这些教程和示例并对它们进行了修改:
https://www.boost.org/doc/libs/1_71_0/doc/html/boost_asio/example/cpp11/multicast/receiver.cpp
https://www.boost.org/doc/libs/1_71_0/doc/html/boost_asio/example/cpp11/multicast/sender.cpp
https://www.boost.org/doc/libs/1_71_0/doc/html/boost_asio/example/cpp11/futures/daytime_client.cpp
https://www.boost.org/doc/libs/1_71_0/doc/html/boost_asio/tutorial/tutdaytime6.html
期货日间客户端和日间服务器工作得很好,除非我使用多播地址,我必须这样做。它只是不交流。
我修改了客户端的日间函数和服务器示例的构造函数,看起来像这样:
客户:
void get_daytime(boost::asio::io_context& io_context,
const boost::asio::ip::address& listenAddress,
const boost::asio::ip::address& multicastAddress)
{
try
{
udp::socket socket(io_context);
boost::asio::ip::udp::endpoint listenEndpoint(listenAddress, multicastPort);
socket.open(listenEndpoint.protocol());
socket.set_option(boost::asio::ip::udp::socket::reuse_address(true));
socket.bind(listenEndpoint);
socket.set_option(boost::asio::ip::multicast::join_group(multicastAddress));
std::array<char, 1U> send_buf = {{ 0 }};
std::future<std::size_t> send_length =
socket.async_send_to(boost::asio::buffer(send_buf),
listenEndpoint,
boost::asio::use_future);
send_length.get();
std::array<char, 128U> recv_buf{};
udp::endpoint sender_endpoint;
std::future<std::size_t> recv_length =
socket.async_receive_from(
boost::asio::buffer(recv_buf),
sender_endpoint,
boost::asio::use_future);
std::cout.write(
recv_buf.data(),
recv_length.get()); // Blocks until receive is complete.
}
catch (std::system_error& e)
{
std::cerr << e.what() << std::endl;
}
}
服务器:
udp_server(boost::asio::io_context& io_context,
const boost::asio::ip::address& listenAddress,
const boost::asio::ip::address_v4& multicastAddress)
: socket_(io_context)
{
boost::asio::ip::udp::endpoint listenEndpoint(listenAddress, multicastPort);
socket_.open(listenEndpoint.protocol());
socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));
socket_.bind(listenEndpoint);
socket_.set_option(boost::asio::ip::multicast::join_group(multicastAddress));
start_receive();
}
我应该如何修改代码,以使其工作在多播?谢谢。
我找到了解决问题的方法。我不需要修改getDaytime()函数,不过我的udp_server()构造函数现在看起来像这样:
udp_server(boost::asio::io_context& io_context)
: socket_(io_context, udp::endpoint(boost::asio::ip::make_address("0.0.0.0"), 60000))
{
socket_.set_option(boost::asio::ip::multicast::join_group(boost::asio::ip::make_address("239.192.0.1")));
start_receive();
}