在boost中序列化二进制数据失败,出现“无效签名”错误

时间:2013-05-18 06:15:02

标签: c++ boost boost-asio boost-serialization

我很难找到使用boost序列化/ asio通过网络发送对象的正确方法。 message类尽可能简单。这不是C ++友好的,也不适合我的需求,我只是暂时保持简单来测试asio / ser:

class message {
    friend class boost::serialization::access;
public:
    message(){}
    int type;
    int sender;
    int assignment;
    int nogood;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & type;
        ar & sender;
        ar & assignment;
        ar & nogood;
    }
};

在客户端,当代理决定发送消息时,通过它的tcp连接将其发送到服务器:

message m;
// do something to generate message
boost::asio::streambuf bufx;
std::ostream os( &bufx );
boost::archive::binary_oarchive ar( os );
ar & m;
boost::asio::write( socket, bufx);

服务器端代码:

boost::asio::streambuf bufx;
std::istream is(&bufx);
boost::archive::binary_iarchive ia(is);  // <--- Exception: invalid signature
size_t rcx = asio::read(socket,bufx);
message m;
ia >> m;

2 个答案:

答案 0 :(得分:2)

我有同样的例外。

This official example帮助我。

如果您仍然遇到麻烦,请尝试此操作。

size_t n = sock.receive(bufs);

// received data is "committed" from output sequence to input sequence
b.commit(n);

std::istream is(&b);
std::string s;
is >> s;

就我而言,我使用async_read。实际上,我修改了example

  boost::asio::streambuf inbound_;
  boost::asio::streambuf::mutable_buffers_type bufs = inbound_.prepare(inbound_data_size);
  void (connection::*f)(
      const boost::system::error_code&, std::size_t,
      T&, boost::tuple<Handler>)
    = &connection::handle_read_data<T, Handler>;
  boost::asio::async_read(socket_, boost::asio::buffer(bufs), 
    boost::bind(f, this,
      boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, boost::ref(t), handler));

然后在处理程序

  /// Handle a completed read of message data.
  template <typename T, typename Handler>
  void handle_read_data(const boost::system::error_code& e, std::size_t bytes_transferred,
      T& t, boost::tuple<Handler> handler)
  {
    if (e)
    {
      boost::get<0>(handler)(e);
    }
    else
    {
      // Extract the data structure from the data just received.
      try
      {
        inbound_.commit(bytes_transferred);
        std::istream archive_stream(&inbound_);
        boost::archive::binary_iarchive archive(archive_stream);
        archive >> t;
      }
      catch (std::exception& err)
      {
        // 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);
    }
  }

答案 1 :(得分:1)

在服务器端代码中,创建二进制存档时streambuf为空。如果归档构造函数在归档开头查找幻数,则它将找不到它。在构建流和存档之前,尝试通过调用streambuf 来填充boost::asio::read()