Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize and send objects by TCP using boost

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

  • My objects are all serializable, using boost serialization.
  • The TCP server/client is made with boost asio.

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).

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.

Thanks.

-

like image 644
0x26res Avatar asked Nov 03 '10 13:11

0x26res


1 Answers

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);
like image 78
peoro Avatar answered Oct 02 '22 14:10

peoro