Reputation: 9058
Modern boost asio has deprecated the code used in every example I can find. The examples suggest code like this:
const char * host = "www.google.com";
const char * port = "http";
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(host, port);
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;
tcp::socket socket(io_service);
boost::system::error_code error = boost::asio::error::host_not_found;
while (error && endpoint_iterator != end) {
socket.close();
socket.connect(*endpoint_iterator++, error);
}
However, both the iterator and the query are marked deprecated. My google searches to find an example of the new and improved way has come up with nothing so far.
Does anyone either have a modern example to point me to, or can just provide a snippet of how to get that socket open using modern boost asio? I don't like using deprecated methods.
Upvotes: 2
Views: 1267
Reputation: 20936
resolve
which takes query
is deprecated, you are right here. But resolver
has these overloads
results_type resolve(
string_view host,
string_view service);
// and N-th other overloads
where host is IP, and service is port. What is results_type
? It is sequence of endpoints to which you can try to establish the connection.
Your code can be translated to something like this:
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver(io_service);
auto endpoints = resolver.resolve("www.google.com","http"); // [1]
boost::asio::ip::tcp::socket socket(io_service);
boost::system::error_code ec;
auto finalEndpoint = boost::asio::connect(socket,endpoints.begin(),endpoints.end(),ec); // [2]
if (ec) { /*ups, error here */} else { /*socket is connected, read/send data/ */ }
in [1] you are passing host/port of service you want to connect to.
in [2] you call connect
(since 1.64 boost version method) which iterates over all endpoints and establish connection. Then you don't need to write your own loop.
Upvotes: 2