Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost serialization for sockets

I'd like to use boost serialization to send a struct over the network using a socket. I looked at their tutorial (http://www.boost.org/doc/libs/1_60_0/libs/serialization/doc/index.html) but it only shows saving and loading to a file.

I've modified my structs to include the serialize() function and tried using the same technique used in the tutorial for files with my socket, but no luck:

#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>

int sock = socket()...

boost::archive::binary_oarchive oa(sock);
oa << mystruct;

error: no matching function for call to ‘boost::archive::binary_oarchive::binary_oarchive(int&)’

So apparently it doesn't work this way with sockets. I googled and found this example that people were referencing: http://www.boost.org/doc/libs/1_38_0/doc/html/boost_asio/example/serialization/server.cpp

However, if you look at the comments in that example code:

// client. The connection::async_write() function will automatically
// serialize the data structure for us.

Well, I don't want to use asio for anything. I only want to serialize the data (using boost serialization) and send the data over a standard socket

Is the library not intended to be used this way? How can I use boost serialization with standard sockets (without asio)?

like image 296
James Avatar asked Dec 26 '15 18:12

James


2 Answers

The boost archive class constructor requires either a stream or a streambuf object. You can:

  • Build/leverage a stream class that writes to a network socket, e.g. ASIO.
  • Especially if the expected file size is small, you could serialize it to memory (using an ostringstream) and then writing the resulting data from the string to the socket using the normal functions.
like image 93
Javier Martín Avatar answered Oct 27 '22 00:10

Javier Martín


You could use a boost::iostreams::file_descriptor. You can use it with boost::iostreams::stream or boost::iostreams::stream_buf.

Alternatively, consider boost::asio::ip::tcp::iostream to wrap the whole raw sockets instead.

like image 41
sehe Avatar answered Oct 26 '22 23:10

sehe