简体   繁体   English

将asio udp套接字发送到不同的ip地址

[英]Boost asio udp socket sending to different ip address

I have one udp server receiving messages from multiple remote clients. 我有一个udp服务器从多个远程客户端接收消息。 When it receives one message, I copy the endpoint and reply to the client at the same IP address on port 5000 where each client is listening. 当它收到一条消息时,我复制端点并在每个客户端正在侦听的端口5000上的相同IP地址处回复客户端。

I have tried multiple debbuging strategies, and printing the endpoint right before I send the reply message gives me the correct IP address and port. 我尝试了多种debbuging策略,在发送回复消息之前打印端点给了我正确的IP地址和端口。

The sender: 发送方:

    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
                )
            );
        }
            );

On the receiver, I get the udp_remote_endpoint and before sending, I set the socket endpoint: 在接收器上,我得到了udp_remote_endpoint,在发送之前,我设置了套接字端点:

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

For example, this output: 例如,此输出:

192.168.1.131K-131-1559147491761155

Is actually sending to the IP 192.168.1.130. 实际上是发送到IP 192.168.1.130。 The message contents are correct "K-131-1559147491761155" 消息内容正确“K-131-1559147491761155”

Solved! 解决了!

I removed the io_service.post and it worked! 我删除了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
            )
        );
//    }
//);`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM