Accept connections

Server needs to accept clients’ connections. First server creates an acceptor:

  1. ......
  2. boost::asio::io_context io_context;
  3. boost::asio::ip::tcp::acceptor acceptor{
  4. io_context,
  5. boost::asio::ip::tcp::endpoint{boost::asio::ip::tcp::v6(), 3303}};
  6. ......

boost::asio::ip::tcp::acceptor is an instance of basic_socket_acceptor:

  1. class tcp
  2. {
  3. ......
  4. /// The TCP acceptor type.
  5. typedef basic_socket_acceptor<tcp> acceptor;
  6. ......
  7. }

The following constructor of basic_socket_acceptor combines creating socket, setting reuse address, binding & listening functions:

  1. basic_socket_acceptor(boost::asio::io_context& io_context,
  2. const endpoint_type& endpoint, bool reuse_addr = true)
  3. : basic_io_object<BOOST_ASIO_SVC_T>(io_context)
  4. {
  5. ......
  6. }

Then acceptor will accept the clients’ connections. Following simple example just shows client’s address and close the connection:

  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::acceptor acceptor{
  9. io_context,
  10. boost::asio::ip::tcp::endpoint{boost::asio::ip::tcp::v6(), 3303}};
  11. while (1)
  12. {
  13. boost::asio::ip::tcp::socket socket{io_context};
  14. acceptor.accept(socket);
  15. std::cout << socket.remote_endpoint() << " connects to " << socket.local_endpoint() << '\n';
  16. }
  17. }
  18. catch (std::exception& e)
  19. {
  20. std::cerr << e.what() << '\n';
  21. return -1;
  22. }
  23. return 0;
  24. }

The running result is like this:

  1. [::ffff:10.217.242.61]:39290 connects to [::ffff:192.168.35.145]:3303
  2. ......