boost :: asio :: async_resolve问题

Moo*_*ice 4 sockets asynchronous boost-asio c++11

我正在构建一个使用的Socket类boost::asio.首先,我创建了一个connect方法,它接受了主机和端口并将其解析为IP地址.这很好用,所以我决定去看看async_resolve.但是,我的回调总是得到一个错误代码995(使用与它同步工作时相同的目标主机/端口).

代码:

启动解决方案的功能:

  // 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
Run Code Online (Sandbox Code Playgroud)

调用此函数的代码:

  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
Run Code Online (Sandbox Code Playgroud)

message()该功能error_code为:

The I/O operation has been aborted because of either a thread exit or an application request
Run Code Online (Sandbox Code Playgroud)

main.cpp看起来像这样:

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;
}
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Sam*_*ler 9

您的resolver对象超出范围,将其移动到Socket类的成员并创建resolveHost方法而不是自由函数.

这是因为boost::asio::ip::tcp::resolver的typedef的一个basic_resolver,它继承basic_io_object.当解析器超出范围时,在发布处理程序之前~basic_io_object() 销毁底层解析程序服务.

无论异步操作是否立即完成,都不会从此函数中调用处理程序.处理程序的调用将以与使用boost :: asio :: io_service :: post()等效的方式执行.

  • @ Moo-Juice没问题,很乐意帮忙.有时你只需要第二组眼睛. (2认同)