network.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #include <boost/asio.hpp>
  2. using boost::asio::ip::tcp;
  3. #include <mutex>
  4. #include <boost/lexical_cast.hpp>
  5. using socket_t = boost::asio::ip::tcp::socket;
  6. void accept_conncections_from_Pb(boost::asio::io_context&io_context, std::vector<socket_t>& socketsPb, int port, size_t j)
  7. {
  8. tcp::acceptor acceptor_a(io_context, tcp::endpoint(tcp::v4(), port));
  9. tcp::socket sb_a(acceptor_a.accept());
  10. socketsPb[j] = std::move(sb_a);
  11. }
  12. void make_connections(bool& party, const std::string host1,
  13. const std::string host2, boost::asio::io_context&io_context, std::vector<socket_t>& socketsPb, std::vector<socket_t>& socketsP2, std::vector<int> ports, std::vector<int> ports2_1, std::vector<int> ports2_0, size_t number_of_sockets)
  14. {
  15. tcp::resolver resolver(io_context);
  16. for(size_t j = 0; j < number_of_sockets + 1; ++j)
  17. {
  18. tcp::socket emptysocket(io_context);
  19. socketsPb.emplace_back(std::move(emptysocket));
  20. }
  21. socketsPb.reserve(number_of_sockets + 1);
  22. for(size_t j = 0; j < number_of_sockets; ++j)
  23. {
  24. int port = 6000;
  25. ports.push_back(port + j);
  26. }
  27. for(size_t j = 0; j < number_of_sockets; ++j)
  28. {
  29. int port = 20000;
  30. ports2_0.push_back(port + j);
  31. }
  32. for(size_t j = 0; j < number_of_sockets; ++j)
  33. {
  34. int port = 40000;
  35. ports2_1.push_back(port + j);
  36. }
  37. #if (PARTY == 0)
  38. party = false;
  39. for(size_t j = 0; j < number_of_sockets; ++j)
  40. {
  41. tcp::socket sb_a(io_context);
  42. boost::asio::connect(sb_a, resolver.resolve({host2, std::to_string(ports2_0[j])}));
  43. socketsP2.emplace_back(std::move(sb_a));
  44. }
  45. for(size_t j = 0; j < number_of_sockets; ++j)
  46. {
  47. tcp::socket sb_a(io_context);
  48. boost::asio::connect(sb_a, resolver.resolve({host1, std::to_string(ports[j])}));
  49. socketsPb[j] = std::move(sb_a);
  50. }
  51. #else
  52. party = true;
  53. for(size_t j = 0; j < number_of_sockets; ++j)
  54. {
  55. tcp::socket sb_a(io_context);
  56. boost::asio::connect(sb_a, resolver.resolve({host2, std::to_string(ports2_1[j])}));
  57. socketsP2.emplace_back(std::move(sb_a));
  58. }
  59. boost::asio::thread_pool pool_connections(number_of_sockets);
  60. for(size_t j = 0; j < number_of_sockets; ++j)
  61. {
  62. boost::asio::post(pool_connections, std::bind(accept_conncections_from_Pb, std::ref(io_context), std::ref(socketsPb), ports[j], j));
  63. }
  64. pool_connections.join();
  65. #endif
  66. }