user1810087 user1810087 - 2 months ago 19
C++ Question

difference between socket.connect and boost::asio::connect

i'm using boost asio for some network communication and wondering why in the examples are sometimes using the

and sometimes the
boost::asio::connect(socket, endpoint)
. according to the code boost::asio::connect is calling the socket.connect in a loop for endpoint iterators. so my question is:

which is better behaviour? using boost::asio::connect or socket.connect? i prefer the socket.connect, because i have just one endpoint. or may i'm wrong and misunderstood the asio libs.

and my second question is, why the endpoint is an iterator? how can it be possible, more then one connections when 1 ip and 1 port is given?

also there is a boost::asio::write and socket.write...

the examples are:

  1. boost::asio::connect(socket, endpoint) blocking_tcp_echo_client.cpp.

  2. socket.connect(endpoint) (a bit older but still working) Daytime.1


boost::asio::connect() is a higher level free function that will invoke boost::asio::ip::tcp::socket::connect(). The documentation is fairly clear here

This function attempts to connect a socket to one of a sequence of endpoints. It does this by repeated calls to the socket's connect member function, once for each endpoint in the sequence, until a connection is successfully established.

Neither has better behavior, though that is largely a subjective term. It's up to you and your application how you want to handle connection establishment. If you need to provide some sort of feedback to the user, ex: "attempting to connect to host 1 of 10" it might be preferable to use socket.connect() in a loop rather than the connect() free function.

The connect() free function takes an endpoint iterator so it can connect to all possible endpoints that are resolved. The tcp echo client that you linked to does this

tcp::resolver resolver(io_service);
tcp::resolver::query query(tcp::v4(), argv[1], argv[2]);
tcp::resolver::iterator iterator = resolver.resolve(query);

tcp::socket s(io_service);
boost::asio::connect(s, iterator);