如何使用boost asio异步读/写到std iostream

时间:2016-11-12 00:16:06

标签: c++ boost-asio

我有客户端 - 服务器应用程序。当我发送几KB数据时,我没有遇到任何问题,但是当数据增长到2-4 MB时,数据传输速度极大地降低了。 我修改了example并使用text_archive(因为this)来序列化我的数据结构,但它对我没有帮助。看起来写入2-4 MB到text_archive需要6-7秒,从text_archive读取需要10-18秒。我的结构包含很少的向量并且有更多的数据,但是常见的实现看起来像这样:

template <typename Archive>
  void serialize(Archive& ar, const unsigned int version)
  {
    ar & code;
    ar & name;
    ...
  }

但为什么需要这么久?我不知道。我不得不拒绝这种做法。

我搜索了解决方案,可能我发现了它。它是std :: istream / ostream。但我的实施似乎是一种拐杖。 这是我的代码:

class connection
{
private:
  /// The underlying socket.
  boost::asio::ip::tcp::socket socket_;

  /// binary stream in
  boost::asio::streambuf readStreambuf;
  std::istream readStream;

  /// binary stream out
  boost::asio::streambuf writeStreambuf;
  std::ostream writeStream;
public:
  /// Constructor.
  connection(boost::asio::io_service& io_service)
      : socket_(io_service), readStream(&readStreambuf), writeStream(&writeStreambuf)
  {

  }

  ...

  /// Asynchronously write a data structure to the socket.
  template <typename T, typename Handler>
  void async_write(const T& t, Handler handler)
  {
      writeStream.clear();
      writeStream << t;
      writeStream << "Close connection \r\n\r\n";

      //is it make sense?     
      socket_.set_option(boost::asio::ip::tcp::no_delay(true));
      boost::system::error_code ec;
      socket_.set_option(boost::asio::socket_base::send_buffer_size(1024 * 1024 * 5), ec);
      //

      boost::asio::async_write(socket_, writeStreambuf, handler);
  }

  /// Asynchronously read a data structure from the socket.
  template <typename T, typename Handler>
  void async_read(T& t, Handler handler)
  {
      void (connection::*func)(const boost::system::error_code&, T&, boost::tuple<Handler>) = &connection::handle_read_stream<T, Handler>;

      boost::asio::async_read_until(socket_, readStreambuf, "Close connection \r\n\r\n", boost::bind(func, this, boost::asio::placeholders::error, boost::ref(t), boost::make_tuple(handler)));
  }

  template <typename T, typename Handler>
  void handle_read_stream(const boost::system::error_code& e,
      T& t, boost::tuple<Handler> handler)
  {
      if (e)
      {
          boost::get<0>(handler)(e);
      }
      else
      {
          try
          {
              readStream.clear();
              readStream >> t;
          }
          catch (std::exception& e)
          {
              // Unable to decode data.
              boost::system::error_code error(boost::asio::error::invalid_argument);
              boost::get<0>(handler)(error);
              return;
          }

          // Inform caller that data has been received ok.
          boost::get<0>(handler)(e);
      }
  }

writeStream << treadStream >> t工作得非常快,但我对writeStream << "Close connection \r\n\r\n"感觉不好。这样对吗? 它有效,但我认为这是错误的。 我应该传递字节数吗?但是怎么样?怎么做得好?

0 个答案:

没有答案