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!
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With