使用 boost 通过 TCP 序列化和发送对象

2021-12-28 00:00:00 tcp serialization c++ boost

我正在尝试通过 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);

相关文章