Boost :: asio :: async_resolve Problem

I am creating a Socket class that uses boost::asio . To get started, I made a connect method that took the host and port and resolved it to an IP address. This worked well, so I decided to look at async_resolve . However, my callback always gets error code 995 (using the same destination host / port as when working synchronously).

code

Function that triggers 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 

The code calling 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 

Function message() error_code :

 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!

+4
source share
1 answer

Your resolver object goes out of scope, translates it into a member of the Socket class, and makes the resolveHost method, not a free function.

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

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be called from within this function. The prayer of the handler will be executed in a way equivalent to using the raise :: ASIO :: io_service :: post ().

+9
source

Source: https://habr.com/ru/post/1334783/


All Articles