I am using the latest version of boost and boost.asio.
I have this class:
enum IPVersion
{
IPv4,
IPv6
};
template <IPVersion version = IPv4>
class Connection
{
private:
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver;
boost::asio::ip::tcp::resolver::query query;
boost::asio::ip::tcp::resolver::iterator iterator;
public:
Connection(std::string host, std::string port);
virtual void connect() { iterator = resolver.resolve(query); } // Is this the moment where the client actually connects?
virtual void disconnect() { /* what goes in here? */ }
};
Should I call io_service::stop() and then on my Connection::connect() call io_service::reset() first before I resolve the query?
Generally, once you’ve made a call to
io_service::run, there’s often few reasons to callio_service::stoporio_service::reset.In your code above, the
connectmethod is not going to actively establish a connection –tcp::resolver::resolvemerely turns a query (such as a hostname, or an IP address, etc.) into a TCP endpoint which can be used to connect a socket. You typically need to dereference an iterator returned byresolver::resolveand pass it to aboost::asio::ip::tcp::socketobject’sconnectmethod (or one of the asynchronous varieties) to connect an endpoint.The Asio tutorials have a good example of this. See the first synchronous TCP daytime server example here: http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/tutorial/tutdaytime1.html. Note that the code first runs:
to turn a query object into a TCP endpoint, and then:
to connect a socket object on that endpoint.
As for what should go in your
disconnectmethod, that’s entirely dependent on the application. But usually you’ll need to keep track of an active connection by encapsulating asocketobject, which you can close as necessary when you calldisconnect. For an example of this, have a look at the tutorial titled “Daytime 3 – An Asynchronous TCP daytime server” here: http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/tutorial/tutdaytime3.html