我试图使用boost :: asio创建一个异步UDP客户端
我在互联网上获得了一些代码,并且设法发送了消息。
但是我的客户端没有收到来自服务器的消息(当我不使用boost时它可以工作)。
这是我的代码
class udp_async_client
{
public:
udp_async_client (boost::asio::io_service& io_service, std::string& host, std:: string port, char **av , int ac)
: reply ()
, _io_service (io_service)
, _sock (io_service, udp:: endpoint (udp:: v4 (), 0)) {
udp:: resolver resolver (_io_service);
udp:: resolver:: query query (udp:: v4 (), host, port);
udp:: resolver:: iterator endpoint_iterator = resolver.resolve (query);
sender_endpoint = *endpoint_iterator;
_io_service.run ();
//test request string
using namespace std;
std::string request = av[3];
for (int i = 4 ; i < ac ; ++i)
{
request += ";";
request += av[i];
}
std:: cout <<"Request is:" <<request <<std:: endl;
_sock.async_send_to (boost:: asio:: buffer (request.c_str(), request.length())
, sender_endpoint
, boost:: bind (&udp_async_client::handle_send_to_server
, this, boost:: asio:: placeholders:: error
, endpoint_iterator));
}
~udp_async_client () {
_io_service.stop ();
}
void handle_receive_from (const boost::system::error_code& error,
size_t bytes_recvd) {}
void handle_receive_from (const boost::system::error_code& error,
size_t bytes_recvd) {}
void handle_send_to_server (const boost::system::error_code& e,
udp:: resolver:: iterator endpoint_iterator) {
std:: cout <<"Handle send to" <<std:: endl;
char reply [max_length] = {};
_sock.async_receive_from (
boost:: asio:: buffer (reply, max_length), sender_endpoint,
boost:: bind (&udp_async_client::handle_receive_from, this,
boost:: asio:: placeholders:: error,
boost::asio::placeholders::bytes_transferred));
std:: cout <<"Reply is:" <<reply <<std:: endl;
}
private:
char reply [max_length];
boost::asio::io_service& _io_service;
udp:: socket _sock;
boost:: asio:: ip:: udp:: endpoint sender_endpoint;
};
和我的主要:
int main (int ac, char** av) {
if (ac < 5) {
std:: cerr <<"Usage: nonblocking_udp_echo_client <host> <port> <name> <name to reach> \n";
return 1;
}
boost:: asio:: io_service io_service;
std:: string host (av[1]);
std:: string port (av[2]);
while (true)
{
udp_async_client cli (io_service, host, port, av , ac);
boost:: this_thread:: sleep (boost:: posix_time:: millisec (500));
}
return 0;
}
我不知道我做错了什么...
最佳答案
_io_service.run()是阻止调用。在io_service上调用stop之前,您的代码实际上并未通过该行。
关于c++ - 使用boost::asio制作一个异步UDP客户端,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11034188/