tcp.hpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //
  2. // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/boostorg/beast
  8. //
  9. #ifndef BOOST_BEAST_TEST_TCP_HPP
  10. #define BOOST_BEAST_TEST_TCP_HPP
  11. #include <boost/beast/core/detail/config.hpp>
  12. #include <boost/beast/core/detail/get_io_context.hpp>
  13. #include <boost/beast/_experimental/unit_test/suite.hpp>
  14. #include <boost/beast/_experimental/test/handler.hpp>
  15. #include <boost/asio/ip/tcp.hpp>
  16. #include <chrono>
  17. namespace boost {
  18. namespace beast {
  19. namespace test {
  20. /** Connect two TCP sockets together.
  21. */
  22. template<class Executor>
  23. bool
  24. connect(
  25. net::basic_stream_socket<net::ip::tcp, Executor>& s1,
  26. net::basic_stream_socket<net::ip::tcp, Executor>& s2)
  27. {
  28. auto ioc1 = beast::detail::get_io_context(s1);
  29. auto ioc2 = beast::detail::get_io_context(s2);
  30. if(! BEAST_EXPECT(ioc1 != nullptr))
  31. return false;
  32. if(! BEAST_EXPECT(ioc2 != nullptr))
  33. return false;
  34. if(! BEAST_EXPECT(ioc1 == ioc2))
  35. return false;
  36. auto& ioc = *ioc1;
  37. try
  38. {
  39. net::basic_socket_acceptor<
  40. net::ip::tcp, Executor> a(s1.get_executor());
  41. auto ep = net::ip::tcp::endpoint(
  42. net::ip::make_address_v4("127.0.0.1"), 0);
  43. a.open(ep.protocol());
  44. a.set_option(
  45. net::socket_base::reuse_address(true));
  46. a.bind(ep);
  47. a.listen(0);
  48. ep = a.local_endpoint();
  49. a.async_accept(s2, test::success_handler());
  50. s1.async_connect(ep, test::success_handler());
  51. run(ioc);
  52. if(! BEAST_EXPECT(
  53. s1.remote_endpoint() == s2.local_endpoint()))
  54. return false;
  55. if(! BEAST_EXPECT(
  56. s2.remote_endpoint() == s1.local_endpoint()))
  57. return false;
  58. }
  59. catch(std::exception const& e)
  60. {
  61. beast::unit_test::suite::this_suite()->fail(
  62. e.what(), __FILE__, __LINE__);
  63. return false;
  64. }
  65. return true;
  66. }
  67. } // test
  68. } // beast
  69. } // boost
  70. #endif