connection.hpp 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. //
  2. // connection.hpp
  3. // ~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #ifndef SERIALIZATION_CONNECTION_HPP
  11. #define SERIALIZATION_CONNECTION_HPP
  12. #include <boost/asio.hpp>
  13. #include <boost/archive/text_iarchive.hpp>
  14. #include <boost/archive/text_oarchive.hpp>
  15. #include <boost/bind.hpp>
  16. #include <boost/shared_ptr.hpp>
  17. #include <boost/tuple/tuple.hpp>
  18. #include <iomanip>
  19. #include <string>
  20. #include <sstream>
  21. #include <vector>
  22. namespace s11n_example {
  23. /// The connection class provides serialization primitives on top of a socket.
  24. /**
  25. * Each message sent using this class consists of:
  26. * @li An 8-byte header containing the length of the serialized data in
  27. * hexadecimal.
  28. * @li The serialized data.
  29. */
  30. class connection
  31. {
  32. public:
  33. /// Constructor.
  34. connection(const boost::asio::executor& ex)
  35. : socket_(ex)
  36. {
  37. }
  38. /// Get the underlying socket. Used for making a connection or for accepting
  39. /// an incoming connection.
  40. boost::asio::ip::tcp::socket& socket()
  41. {
  42. return socket_;
  43. }
  44. /// Asynchronously write a data structure to the socket.
  45. template <typename T, typename Handler>
  46. void async_write(const T& t, Handler handler)
  47. {
  48. // Serialize the data first so we know how large it is.
  49. std::ostringstream archive_stream;
  50. boost::archive::text_oarchive archive(archive_stream);
  51. archive << t;
  52. outbound_data_ = archive_stream.str();
  53. // Format the header.
  54. std::ostringstream header_stream;
  55. header_stream << std::setw(header_length)
  56. << std::hex << outbound_data_.size();
  57. if (!header_stream || header_stream.str().size() != header_length)
  58. {
  59. // Something went wrong, inform the caller.
  60. boost::system::error_code error(boost::asio::error::invalid_argument);
  61. boost::asio::post(socket_.get_executor(), boost::bind(handler, error));
  62. return;
  63. }
  64. outbound_header_ = header_stream.str();
  65. // Write the serialized data to the socket. We use "gather-write" to send
  66. // both the header and the data in a single write operation.
  67. std::vector<boost::asio::const_buffer> buffers;
  68. buffers.push_back(boost::asio::buffer(outbound_header_));
  69. buffers.push_back(boost::asio::buffer(outbound_data_));
  70. boost::asio::async_write(socket_, buffers, handler);
  71. }
  72. /// Asynchronously read a data structure from the socket.
  73. template <typename T, typename Handler>
  74. void async_read(T& t, Handler handler)
  75. {
  76. // Issue a read operation to read exactly the number of bytes in a header.
  77. void (connection::*f)(
  78. const boost::system::error_code&,
  79. T&, boost::tuple<Handler>)
  80. = &connection::handle_read_header<T, Handler>;
  81. boost::asio::async_read(socket_, boost::asio::buffer(inbound_header_),
  82. boost::bind(f,
  83. this, boost::asio::placeholders::error, boost::ref(t),
  84. boost::make_tuple(handler)));
  85. }
  86. /// Handle a completed read of a message header. The handler is passed using
  87. /// a tuple since boost::bind seems to have trouble binding a function object
  88. /// created using boost::bind as a parameter.
  89. template <typename T, typename Handler>
  90. void handle_read_header(const boost::system::error_code& e,
  91. T& t, boost::tuple<Handler> handler)
  92. {
  93. if (e)
  94. {
  95. boost::get<0>(handler)(e);
  96. }
  97. else
  98. {
  99. // Determine the length of the serialized data.
  100. std::istringstream is(std::string(inbound_header_, header_length));
  101. std::size_t inbound_data_size = 0;
  102. if (!(is >> std::hex >> inbound_data_size))
  103. {
  104. // Header doesn't seem to be valid. Inform the caller.
  105. boost::system::error_code error(boost::asio::error::invalid_argument);
  106. boost::get<0>(handler)(error);
  107. return;
  108. }
  109. // Start an asynchronous call to receive the data.
  110. inbound_data_.resize(inbound_data_size);
  111. void (connection::*f)(
  112. const boost::system::error_code&,
  113. T&, boost::tuple<Handler>)
  114. = &connection::handle_read_data<T, Handler>;
  115. boost::asio::async_read(socket_, boost::asio::buffer(inbound_data_),
  116. boost::bind(f, this,
  117. boost::asio::placeholders::error, boost::ref(t), handler));
  118. }
  119. }
  120. /// Handle a completed read of message data.
  121. template <typename T, typename Handler>
  122. void handle_read_data(const boost::system::error_code& e,
  123. T& t, boost::tuple<Handler> handler)
  124. {
  125. if (e)
  126. {
  127. boost::get<0>(handler)(e);
  128. }
  129. else
  130. {
  131. // Extract the data structure from the data just received.
  132. try
  133. {
  134. std::string archive_data(&inbound_data_[0], inbound_data_.size());
  135. std::istringstream archive_stream(archive_data);
  136. boost::archive::text_iarchive archive(archive_stream);
  137. archive >> t;
  138. }
  139. catch (std::exception& e)
  140. {
  141. // Unable to decode data.
  142. boost::system::error_code error(boost::asio::error::invalid_argument);
  143. boost::get<0>(handler)(error);
  144. return;
  145. }
  146. // Inform caller that data has been received ok.
  147. boost::get<0>(handler)(e);
  148. }
  149. }
  150. private:
  151. /// The underlying socket.
  152. boost::asio::ip::tcp::socket socket_;
  153. /// The size of a fixed length header.
  154. enum { header_length = 8 };
  155. /// Holds an outbound header.
  156. std::string outbound_header_;
  157. /// Holds the outbound data.
  158. std::string outbound_data_;
  159. /// Holds an inbound header.
  160. char inbound_header_[header_length];
  161. /// Holds the inbound data.
  162. std::vector<char> inbound_data_;
  163. };
  164. typedef boost::shared_ptr<connection> connection_ptr;
  165. } // namespace s11n_example
  166. #endif // SERIALIZATION_CONNECTION_HPP