2
0

NetworkClient.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /*
  2. * NetworkClient.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "NetworkClient.h"
  12. #include "NetworkConnection.h"
  13. VCMI_LIB_NAMESPACE_BEGIN
  14. DLL_LINKAGE bool checkNetworkPortIsFree(const std::string & host, uint16_t port)
  15. {
  16. boost::asio::io_service io;
  17. NetworkAcceptor acceptor(io);
  18. boost::system::error_code ec;
  19. acceptor.open(boost::asio::ip::tcp::v4(), ec);
  20. if (ec)
  21. return false;
  22. acceptor.bind(boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port), ec);
  23. if (ec)
  24. return false;
  25. return true;
  26. }
  27. NetworkClient::NetworkClient(INetworkClientListener & listener)
  28. : io(new NetworkService)
  29. , socket(new NetworkSocket(*io))
  30. , listener(listener)
  31. {
  32. }
  33. void NetworkClient::start(const std::string & host, uint16_t port)
  34. {
  35. boost::asio::ip::tcp::resolver resolver(*io);
  36. auto endpoints = resolver.resolve(host, std::to_string(port));
  37. boost::asio::async_connect(*socket, endpoints, std::bind(&NetworkClient::onConnected, this, _1));
  38. }
  39. void NetworkClient::onConnected(const boost::system::error_code & ec)
  40. {
  41. if (ec)
  42. {
  43. listener.onConnectionFailed(ec.message());
  44. return;
  45. }
  46. connection = std::make_shared<NetworkConnection>(socket, *this);
  47. connection->start();
  48. listener.onConnectionEstablished(connection);
  49. }
  50. void NetworkClient::run()
  51. {
  52. boost::asio::executor_work_guard<decltype(io->get_executor())> work{io->get_executor()};
  53. io->run();
  54. }
  55. void NetworkClient::poll()
  56. {
  57. io->poll();
  58. }
  59. void NetworkClient::stop()
  60. {
  61. io->stop();
  62. }
  63. void NetworkClient::setTimer(std::chrono::milliseconds duration)
  64. {
  65. auto timer = std::make_shared<NetworkTimer>(*io, duration);
  66. timer->async_wait([this, timer](const boost::system::error_code& error){
  67. if (!error)
  68. listener.onTimer();
  69. });
  70. }
  71. void NetworkClient::sendPacket(const std::vector<uint8_t> & message)
  72. {
  73. connection->sendPacket(message);
  74. }
  75. void NetworkClient::onDisconnected(const std::shared_ptr<NetworkConnection> & connection)
  76. {
  77. listener.onDisconnected(connection);
  78. }
  79. void NetworkClient::onPacketReceived(const std::shared_ptr<NetworkConnection> & connection, const std::vector<uint8_t> & message)
  80. {
  81. listener.onPacketReceived(connection, message);
  82. }
  83. VCMI_LIB_NAMESPACE_END