2011-01-08 325 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