gpt4 book ai didi

c++ - 在 boost 中序列化二进制数据失败,出现 `invalid signature' 错误

转载 作者:行者123 更新时间:2023-11-30 02:55:13 25 4
gpt4 key购买 nike

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

最佳答案

我遇到了同样的异常。

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);
}
}

关于c++ - 在 boost 中序列化二进制数据失败,出现 `invalid signature' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16621317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com