views:

83

answers:

1

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?

+1  A: 

Generally, once you've made a call to io_service::run, there's often few reasons to call io_service::stop or io_service::reset.

In your code above, the connect method is not going to actively establish a connection - tcp::resolver::resolve merely 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 by resolver::resolve and pass it to a boost::asio::ip::tcp::socket object's connect method (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:

tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

to turn a query object into a TCP endpoint, and then:

socket.connect(*endpoint_iterator++, error);

to connect a socket object on that endpoint.

As for what should go in your disconnect method, that's entirely dependent on the application. But usually you'll need to keep track of an active connection by encapsulating a socket object, which you can close as necessary when you call disconnect. 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

bjlaub