Connect server

The client can use the endpoints returned by DNS query to connect server application. The following is an example:

  1. #include <boost/asio.hpp>
  2. #include <iostream>
  3. int main()
  4. {
  5. try
  6. {
  7. boost::asio::io_context io_context;
  8. boost::asio::ip::tcp::resolver resolver{io_context};
  9. boost::asio::ip::tcp::resolver::results_type endpoints =
  10. resolver.resolve("google.com", "https");
  11. boost::asio::ip::tcp::tcp::socket socket{io_context};
  12. auto endpoint = boost::asio::connect(socket, endpoints);
  13. std::cout << "Connect to " << endpoint << " successfully!\n";
  14. }
  15. catch (std::exception& e)
  16. {
  17. std::cerr << e.what() << '\n';
  18. return -1;
  19. }
  20. return 0;
  21. }

The running result is like following:

  1. Connect to 172.217.194.101:443 successfully!

Please notice boost::asio::connect requires the iterator of endpoints. If you just want one specified endpoint, you can use connect member function of socket. Check following code:

  1. #include <boost/asio.hpp>
  2. #include <iostream>
  3. int main()
  4. {
  5. try
  6. {
  7. boost::asio::io_context io_context;
  8. boost::asio::ip::tcp::resolver resolver{io_context};
  9. boost::asio::ip::tcp::resolver::results_type endpoints =
  10. resolver.resolve("google.com", "https");
  11. boost::asio::ip::tcp::tcp::socket socket{io_context};
  12. auto eit = endpoints.cbegin();
  13. for (; eit != endpoints.cend(); eit++)
  14. {
  15. boost::system::error_code ec;
  16. boost::asio::ip::tcp::endpoint endpoint = *eit;
  17. socket.connect(endpoint, ec);
  18. if (!ec)
  19. {
  20. std::cout << "Connect to " << endpoint << " successfully!\n";
  21. break;
  22. }
  23. }
  24. if (eit == endpoints.cend())
  25. {
  26. std::cout << "Connect failed!\n";
  27. return -1;
  28. }
  29. }
  30. catch (std::exception& e)
  31. {
  32. std::cerr << e.what() << '\n';
  33. return -1;
  34. }
  35. return 0;
  36. }

The running result is like this:

  1. Connect to 172.217.194.139:443 successfully!