使用Boost.asio将UDP数据包发送到公共IP

时间:2012-06-29 05:37:49

标签: c++ tcp udp boost-asio p2p

我想将UDP数据包发送到我的静态IP 122.***.***.***,其中UDP服务器侦听端口1213.

udp::resolver resolver(io_serviceSend);
    udp::resolver::query query(udp::v4(),"122.***.***.***","1213");
    udp::endpoint receiver_endpoint = *resolver.resolve(query);

    udp::socket socket(io_serviceSend);
    socket.open(udp::v4());

    boost::shared_ptr<std::string> message(new std::string("Transfer"));

    socket.send_to(boost::asio::buffer(*message), receiver_endpoint);

但这失败了。是因为我将它发送到私有端口而不是将其发送到NAT的端口。但对于TCP来说,它完美无缺。 有人可以解释我的理论或发布一个良好的链接。

我的服务器代码是

UDPTunnel::UDPTunnel(boost::asio::io_service& io_service)
:socket_(io_service, udp::endpoint(udp::v4(), 1213))
{
start_receive();
}

void UDPTunnel::start_receive()
{
    socket_.async_receive_from(
            boost::asio::buffer(recv_buffer_), remote_endpoint_,
            boost::bind(&UDPTunnel::handle_receive, this,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
    cout << "\nUDP Started To Listening";
}

void UDPTunnel::handle_receive(const boost::system::error_code& error,std::size_t)
{
 cout << "\nUDP Recieved Message";
 if (!error || error == boost::asio::error::message_size)
  {
  cout << "\nRecieved Message";
  }

}

0 个答案:

没有答案