boost::asio::async_resolve Problem

孤者浪人 提交于 2020-01-03 17:04:13

问题


I'm in the process of constructing a Socket class that uses boost::asio. To start with, I made a connect method that took a host and a port and resolved it to an IP address. This worked well, so I decided to look in to async_resolve. However, my callback always gets an error code of 995 (using the same destination host/port as when it worked synchronously).

code:

Function that starts the resolution:

  // resolve a host asynchronously
  template<typename ResolveHandler>
  void resolveHost(const String& _host, Port _port, ResolveHandler _handler) const
  {
   boost::asio::ip::tcp::endpoint ret;
   boost::asio::ip::tcp::resolver::query query(_host, boost::lexical_cast<std::string>(_port));
   boost::asio::ip::tcp::resolver r(m_IOService);
   r.async_resolve(query, _handler);
  }; // eo resolveHost

Code that calls this function:

  void Socket::connect(const String& _host, Port _port)
  {
   // Anon function for resolution of the host-name and asynchronous calling of the above
   auto anonResolve = [this](const boost::system::error_code& _errorCode, 
           boost::asio::ip::tcp::resolver_iterator _epIt)
   {
    // raise event
    onResolve.raise(SocketResolveEventArgs(*this, !_errorCode ? (*_epIt).host_name() : String(""), _errorCode));

    // perform connect, calling back to anonymous function
    if(!_errorCode)
     connect(*_epIt);
   };

   // Resolve the host calling back to anonymous function
   Root::instance().resolveHost(_host, _port, anonResolve);

  }; // eo connect

The message() function of the error_code is:

The I/O operation has been aborted because of either a thread exit or an application request

And my main.cpp looks like this:

int _tmain(int argc, _TCHAR* argv[])
{
 morse::Root root;
 TextSocket s;
 s.connect("somehost.com", 1234);
 while(true)
 {
  root.performIO(); // calls io_service::run_one()
 }
 return 0;
}

Thanks in advance!


回答1:


Your resolver object is going out of scope, move it to a member of the Socket class and make resolveHost a method rather than free function.

This happens because boost::asio::ip::tcp::resolver is a typedef of a basic_resolver, which inherits from basic_io_object. When the resolver goes out of scope, ~basic_io_object() destroys the underlying resolver service before your handler can be posted.

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().



来源:https://stackoverflow.com/questions/4636608/boostasioasync-resolve-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!