James
James

Reputation: 101

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

Upvotes: 6

Views: 1811

Answers (2)

sehe
sehe

Reputation: 393134

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.

Upvotes: 2

Javier Mart&#237;n
Javier Mart&#237;n

Reputation: 2605

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.

Upvotes: 2

Related Questions