此代码与原始udp异步回显服务器相同,但具有不同的套接字.
响应将在wireshark中传输并显示,但随后会将ICMP Port Unreachable错误发送回服务器.我试图理解为什么因为一切看起来都正确.
您可以将此代码直接复制到源文件中,例如server.cpp.然后用.编译
gcc server.cpp -lboost_system
使用如下命令运行它: ./a.out 35200
#include#include #include #include using boost::asio::ip::udp; class server { public: server(boost::asio::io_service& io_service, short port) : io_service_(io_service), socket_(io_service, udp::endpoint(udp::v4(), port)), socket2_(io_service, udp::endpoint(udp::v4(),0)) { socket_.async_receive_from( boost::asio::buffer(data_, max_length), sender_endpoint_, boost::bind(&server::handle_receive_from, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void handle_receive_from(const boost::system::error_code& error, size_t bytes_recvd) { if (!error && bytes_recvd > 0) { // use a different socket... random source port. socket2_.async_send_to( boost::asio::buffer(data_, bytes_recvd), sender_endpoint_, boost::bind(&server::handle_send_to, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else { socket_.async_receive_from( boost::asio::buffer(data_, max_length), sender_endpoint_, boost::bind(&server::handle_receive_from, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } void handle_send_to(const boost::system::error_code& /*error*/, size_t /*bytes_sent*/) { // error_code shows success when checked here. But wireshark shows // an ICMP response with destination unreachable, port unreachable when run on // localhost. Haven't tried it across a network. socket_.async_receive_from( boost::asio::buffer(data_, max_length), sender_endpoint_, boost::bind(&server::handle_receive_from, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } private: boost::asio::io_service& io_service_; udp::socket socket_; udp::socket socket2_; udp::endpoint sender_endpoint_; enum { max_length = 1024 }; char data_[max_length]; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: async_udp_echo_server \n"; return 1; } boost::asio::io_service io_service; using namespace std; // For atoi. server s(io_service, atoi(argv[1])); io_service.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
我需要这个的原因是因为我有多个线程从一个由UDP服务器提供的输入队列接收数据.现在我希望这些线程能够直接发送响应,但我无法使其正常工作.
如果我在async_send_to调用中使用原始套接字(即socket_),那么它可以工作.
好的......这里的测试客户端不能使用上面的代码(但是使用asio示例中的原始版本).
#!/usr/bin/python import socket, sys, time, struct textport = "35200" host = "localhost" if len(sys.argv) > 1: host = sys.argv[1] print "Sending Data" s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) port = int(textport) s.connect((host, port)) s.sendall("Hello World") #s.shutdown(1) print "Looking for replies; press Ctrl-C or Ctrl-Break to stop." while 1: buf = s.recv(1200) if not len(buf): break print "Received: %s" % buf
这令我感到困惑.但至少我可以使用C++ UDP客户端,它的工作原理.