在 boost 中序列化二进制数据失败,并出现"签名无效"错误
Serializing binary data in boost fails with `invalid signature' error
我很难找出使用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;
我得到了同样的异常。
和这个官方的例子帮助我。
如果你仍然遇到麻烦,试试这个。
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);
}
}
在您的服务器端代码中,当您创建二进制存档时,您的streambuf
为空。如果存档构造函数在存档的开头寻找一个幻数,那么它将找不到它。在构建流和存档之前,尝试用boost::asio::read()
调用填充streambuf
。
相关文章:
- 错误:无效的预处理指令 #i 的意思是 #if?
- is_same和variadic模板编译时错误无效转换
- printf 和 strftime 的参数错误无效
- 错误:无效使用非静态成员函数"int test::hotplug_callback(libusb_contex
- 我收到一个错误无效的操作数,类型为 const char [42] 和二进制"运算符+"的双倍数
- 错误:无效使用无效
- 发布信号量返回错误 6(无效句柄)
- C++17 可选树,错误:无效使用不完整的类型
- C++ 线程函数指针实现返回错误无效使用非静态成员函数
- 在测试中使用unique_ptr时指针错误无效
- 使用 malloc 而不是 new 会导致 free():指针错误无效
- valgrind错误无效读数4
- X11 XGetImage badmatch错误(无效的参数属性)
- free():C++中的指针错误无效
- 使用 valgrind 的地图中的读取大小错误无效
- 错误:无效的基类C
- 错误:无效使用了void表达式C++
- C++链接错误.无效
- free()错误:无效的下一个大小(fast)
- 我收到错误"无效使用不完整的类型'class map'