1

我很难找出使用 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;
4

2 回答 2

2

我有同样的例外。

这个官方的例子对我有帮助。

如果你仍然有麻烦,试试这个。

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。实际上,我修改了示例

  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);
    }
  }
于 2014-04-11T06:10:42.783 回答
1

在您的服务器端代码中,streambuf当您创建二进制存档时,您是空的。如果存档构造函数在存档的开头寻找一个幻数,那么它不会找到它。在构建流和存档之前streambuf尝试用调用来填充。boost::asio::read()

于 2013-05-18T14:10:55.083 回答