6
votes

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

2
Uff, I think you have a huge concept mess. For what I understand, what you intend is to send a file over network, isn't it ? So, you should read first the file and use its stream to send the bytes with the socket. Passing a socket descriptor to the constructor of binary_archive has no sense. - perencia
I have a struct in memory and I need to send the bytes over the wire. I can't just send &myStruct, sizeof(mystruct) because the struct contains pointers. I thought that it was normal to serialize in a case like this. - James

2 Answers

2
votes

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.
2
votes

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.