Boost asio udp套接字发送到不同的IP地址

时间:2019-05-29 16:55:50

标签: c++ sockets udp boost-asio

我有一台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”

1 个答案:

答案 0 :(得分:0)

解决了!

我删除了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
            )
        );
//    }
//);`
相关问题