从socket读取时出现boost.asio错误

时间:2010-10-06 01:08:35

标签: boost boost-asio

以下客户代码:

  typedef boost::array<char, 10> header_packet;
  header_packet header;
  boost::system::error_code error;
  ...
  /** send header */
  boost::asio::write(
     _socket,
     boost::asio::buffer(header, header.size()),
     boost::asio::transfer_all(),
     error
  );
  /** send body */
  boost::asio::write(
     _socket,
     boost::asio::buffer(buffer, buffer.length()),
     boost::asio::transfer_all(),
     error
  );

服务器:

   struct header {
      boost::uint32_t header_length;
      boost::uint32_t id;
      boost::uint32_t body_length;
   };
   static header unpack_header(const header_packet& data) {
      header hdr;
      sscanf(data.data(), "%02d%04d%04d", &hdr.header_length, &hdr.id, &hdr.body_length);
      return hdr;
   }

void connection::start() {
   boost::asio::async_read(
      _socket,
      boost::asio::buffer(_header, _header.size()),
      boost::bind(
         &connection::read_header_handler,
         shared_from_this(),
         boost::asio::placeholders::error
      )
   );
}

/***************************************************************************/

void connection::read_header_handler(const boost::system::error_code& e) {
   if ( !e ) {
      std::cout << "readed header: " << _header.c_array() << std::endl;
      std::cout << constants::unpack_header(_header);
      boost::asio::async_read(
         _socket,
         boost::asio::buffer(_body, constants::unpack_header(_header).body_length),
         boost::bind(
            &connection::read_body_handler,
            shared_from_this(),
            boost::asio::placeholders::error
         )
      );
   } else {
      /** report error */
      std::cout << "read header finished with error: " << e.message() << std::endl;
   }
}

/***************************************************************************/

void connection::read_body_handler(const boost::system::error_code& e) {
   if ( !e ) {
      std::cout << "readed body: " << _body.c_array() << std::endl;
      start();
   } else {
      /** report error */
      std::cout << "read body finished with error: " << e.message() << std::endl;
   }
}

在服务器端调用方法read_header_handler(),但从不调用方法read_body_handler()。虽然客户端已在套接字中写下数据。 标头被成功解码并解码。 什么是错误?

1 个答案:

答案 0 :(得分:0)

问题解决了。

在asio :: write()中发送序列化结果时,我的代码中出现

错误。所以服务器无法读取任何内容。