1

ブースト シリアライゼーション/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 に答える