Serialize and send objects by TCP using boost(使用 boost 通过 TCP 序列化和发送对象)
问题描述
我正在尝试通过 tcp 连接发送 C++ ojbect:
I am trying to send C++ ojbects through a tcp connection:
- 我的对象都是可序列化的,使用 boost 序列化.
- TCP 服务器/客户端是用 boost asio 制作的.
基本上我想发送这样的消息将包含消息类型(被发送对象的类型)和数据本身(序列化对象)和数据的大小,以便我可以处理缓冲区(大小相同类型的对象可能会有所不同,因为它不是 POD).
Basically I would like to send message like that would contain the message type (the type of the object being sent) and the data itself (the serialized object) and the size of the data so I can process the buffer (the size can vary for objects of the same type, as it is not POD).
我有点卡住了,因为我不知道如何发送这个.不明白将数据转换成char缓冲区的步骤是什么,在缓冲区的开头加上额外的信息(消息类型&大小),然后把这个缓冲区交给tcp连接的send函数,所有这些都尽可能少地复制.
I am a bit stuck, because I don't know how I can send this. I don't understand what are the steps to convert the data to a char buffer, and adding the extra information (message type & size) at the beginning of the buffer, and then giving this buffer to the send function of the tcp connection, all that with doing as few copies as possible.
谢谢.
-
推荐答案
这里 你可以找到一个很好的例子,说明如何将 boost::serialization 与 boost::asio 结合使用.
Here you can find a good example on how to use boost::serialization together with boost::asio.
这样的东西是您需要的核心:
Something like this is the core of what you need:
std::ostringstream archive_stream;
boost::archive::text_oarchive archive(archive_stream);
archive << YOUR_DATA;
outbound_data_ = archive_stream.str();
boost::asio::async_write(socket_, boost::asio::buffer(outbound_data_), handler);
这篇关于使用 boost 通过 TCP 序列化和发送对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 boost 通过 TCP 序列化和发送对象


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01