c++ - 使用升压套接字升压序列化失败

标签 c++ boost-asio boost-serialization

我正在尝试反序列化通过 asio 套接字传递的对象,但出现错误: “在抛出‘boost::archive::archive_exception’实例后终止调用 what(): 输入流错误” 当我试图获取数据时:

服务器端:

int main()
{
...
    std::ostringstream oss;
    Note note(20,20);

    boost::archive::text_oarchive oa(oss);
    oa << note;
    std::cout << (char*)&oa << std::endl;
    send_(socket_, (char *)&oa);
}

客户端:

int main()
{
...
    boost::asio::read(socket, receive_buffer, boost::asio::transfer_all(), error);

    std::string myString;

    std::istream(&receive_buffer) >> myString;
    std::istringstream iss(myString);
    boost::archive::text_iarchive ia(iss); <--- input stream error
    ia >> note;
    std::cout << note.denominateur << std::endl;
}

最佳答案

您必须发送 ostringstream 的内容,即包含序列化 Note 的字符串。现在您正在发送 text_oarchive 实例的字节,这对我来说没有任何意义。

它可能看起来像:

  boost::archive::text_oarchive oa(oss);
  oa << note;
  cout << oss.str(); // HERE you get some string which represents serialized Note
  // and content of this string should be sent
  send_(socket_, oss.str().c_str(), oss.str().size());
                 ^^^ content        ^^^ size of content

您的send_ 函数没有大小参数?有趣的是,对我来说,应该使用这个参数来知道必须传输多少字节。

关于客户端:

// [1]
boost::asio::read(socket, receive_buffer, boost::asio::transfer_all(), error);

因为您没有提供 MCVE,我假设您在 [1] 行中将 receive_buffer 创建为某种 dynamic_buffer,如果没有,它只是空字符串将读取空字符串。所以反序列化是行不通的。

关于c++ - 使用升压套接字升压序列化失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56253719/

相关文章:

C++软件传递参数方法

c++ - 无法反序列化 std::list<std::string>

c++ - 制作现有模板类的模板

c++ - Visual C++ 错误 C2143 : syntax error: missing ')' before 'constant'

c++ - 这个变量将如何初始化?

c++ - Boost 序列化和文件 IO 非常慢

C++ 在析构函数中序列化是个坏主意,如果是,为什么?

windows - 在 Windows 上,ICMPv6 回显回复缺少 IP header

c++ - 如何将 asio 与设备文件一起使用

c++ - 绑定(bind)对象未在 VS2015 上编译