NetworkConnection.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * NetworkConnection.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 "NetworkConnection.h"
  12. VCMI_LIB_NAMESPACE_BEGIN
  13. NetworkConnection::NetworkConnection(const std::shared_ptr<NetworkSocket> & socket)
  14. : socket(socket)
  15. {
  16. }
  17. void NetworkConnection::start()
  18. {
  19. boost::asio::async_read(*socket,
  20. readBuffer,
  21. boost::asio::transfer_exactly(messageHeaderSize),
  22. std::bind(&NetworkConnection::onHeaderReceived,this, _1));
  23. }
  24. void NetworkConnection::onHeaderReceived(const boost::system::error_code & ec)
  25. {
  26. uint32_t messageSize = readPacketSize(ec);
  27. boost::asio::async_read(*socket,
  28. readBuffer,
  29. boost::asio::transfer_exactly(messageSize),
  30. std::bind(&NetworkConnection::onPacketReceived,this, _1, messageSize));
  31. }
  32. uint32_t NetworkConnection::readPacketSize(const boost::system::error_code & ec)
  33. {
  34. if (ec)
  35. {
  36. throw std::runtime_error("Connection aborted!");
  37. }
  38. if (readBuffer.size() < messageHeaderSize)
  39. {
  40. throw std::runtime_error("Failed to read header!");
  41. }
  42. std::istream istream(&readBuffer);
  43. uint32_t messageSize;
  44. istream.read(reinterpret_cast<char *>(&messageSize), messageHeaderSize);
  45. if (messageSize > messageMaxSize)
  46. {
  47. throw std::runtime_error("Invalid packet size!");
  48. }
  49. return messageSize;
  50. }
  51. void NetworkConnection::onPacketReceived(const boost::system::error_code & ec, uint32_t expectedPacketSize)
  52. {
  53. if (ec)
  54. {
  55. throw std::runtime_error("Connection aborted!");
  56. }
  57. if (readBuffer.size() < expectedPacketSize)
  58. {
  59. throw std::runtime_error("Failed to read header!");
  60. }
  61. std::vector<uint8_t> message;
  62. message.resize(expectedPacketSize);
  63. std::istream istream(&readBuffer);
  64. istream.read(reinterpret_cast<char *>(message.data()), messageHeaderSize);
  65. start();
  66. }
  67. void NetworkConnection::sendPacket(const std::vector<uint8_t> & message)
  68. {
  69. NetworkBuffer writeBuffer;
  70. std::ostream ostream(&writeBuffer);
  71. uint32_t messageSize = message.size();
  72. ostream.write(reinterpret_cast<const char *>(&messageSize), messageHeaderSize);
  73. ostream.write(reinterpret_cast<const char *>(message.data()), message.size());
  74. boost::asio::write(*socket, writeBuffer );
  75. }
  76. VCMI_LIB_NAMESPACE_END