序列化和使用boost通过TCP发送对象 [英] Serialize and send objects by TCP using boost

查看:574
本文介绍了序列化和使用boost通过TCP发送对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过TCP连接发送C ++ ojbects:

I am trying to send C++ ojbects through a tcp connection:


  • 我的对象都是可序列化的,使用boost序列化。

  • TCP服务器/客户端是由与升压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).

我有点卡住,因为我不知道我怎么能发送此。我不明白什么是将数据转换为字符缓冲区的步骤,并添加额外的信息(消息类型放大器;大小)在缓冲区的开头,然后给这个缓冲TCP连接的发送功能,所有以做尽可能少的副本越好。

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.

感谢。

-

推荐答案

<一个href=\"http://www.boost.org/doc/libs/1_38_0/doc/html/boost_asio/examples.html#boost_asio.examples.serialization\">Here你可以找到关于如何使用的boost :: ASIO一起使用boost ::系列化一个很好的例子。

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发送对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆