首页 > 解决方案 > Boost asio udp socket发送到不同的IP地址

问题描述

我有一台 udp 服务器从多个远程客户端接收消息。当它收到一条消息时,我复制端点并在每个客户端正在侦听的端口 5000 上的相同 IP 地址上回复客户端。

我尝试了多种调试策略,并且在我发送回复消息之前打印端点会给我正确的 IP 地址和端口。

发件人:

    std::cout << udp_remote_endpoint.address().to_string();
    std::string str(packet.begin(), packet.end());
    std::cout << str << std::endl;
    io_service.post(
        [this, packet]()
        {
            udp_socket.async_send_to(
                boost::asio::buffer(packet),
                udp_remote_endpoint,
                boost::bind(
                    &uds::handle_write,
                    this,
                    boost::asio::placeholders::error,
                    boost::asio::placeholders::bytes_transferred
                )
            );
        }
            );

在接收器上,我得到了 udp_remote_endpoint,在发送之前,我设置了套接字端点:

    new_addr.endpoint = socket.get_udp_remote_endpoint();
    new_addr.endpoint.port(5000);
    socket.set_udp_remote_endpoint(new_addr.endpoint);

例如,这个输出:

192.168.1.131K-131-1559147491761155

实际上是发送到IP 192.168.1.130。消息内容正确“K-131-1559147491761155”

标签: c++socketsudpboost-asio

解决方案


解决了!

我删除了io_service.post它,它起作用了!

`std::cout << udp_remote_endpoint.address().to_string();
std::string str(packet.begin(), packet.end());
std::cout << str << std::endl;
//io_service.post(
//    [this, packet]()
//    {
        udp_socket.async_send_to(
            boost::asio::buffer(packet),
            udp_remote_endpoint,
            boost::bind(
                &uds::handle_write,
                this,
                boost::asio::placeholders::error,
                boost::asio::placeholders::bytes_transferred
            )
        );
//    }
//);`

推荐阅读