2011-01-08 321 views
4

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

代码

功能启动分辨率:

// 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 

代码调用该函数:

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 

error_codemessage()功能是:

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

而且我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; 
} 

提前感谢!

回答

9

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

发生这种情况是因为boost::asio::ip::tcp::resolvera typedef of a basic_resolver,which inherits from basic_io_object。当解析器超出范围时,~basic_io_object()destroys之前的底层解析器服务handler can be posted

不管异步 操作是否立即或 未完成时,该处理程序将不能从该函数中调用 。处理程序的调用 将以相当于使用 boost :: asio :: io_service :: post()的 方式执行。

+0

谢谢非常多,应该已经完全明显:) – 2011-01-09 01:13:06