Dmitry
Dmitry

Reputation: 2158

Boost serialization : ensure data safety over socket transmition

I'm using boost 1.53 and serialization to transfer an array of 520 floats over TCP/IP. I put a debug code printout to see the amount of data to be send : it's about 5 K. No problem for me here, but this value somehow depends on the actual data to be serialized. It could be 5400, 5500 and so on.

The question is : what is the right way to receive such data block? For the moment I use read_some() call. But as I've figured out it doesn't guarantee that the whole serialized block of data will be read out. Am I wrong?

How to ensure that there will be a complete archive at RX side? Is there any exception to be thrown when it is not possible to deserialize a chunk of data?

Upvotes: 1

Views: 145

Answers (2)

sehe
sehe

Reputation: 393134

Yes. read_some is potentially a no-op on conforming implementations[1].

Instead do a loop using read() and gcount(), like:

std::istream& is = gotten_from_somewhere_or_a_parameter();

std::vector<byte> v(256);
std::streamsize bytes_read;
do
{
    is.read(v.data(),v.size());
    bytes_read = stream.gcount ();

    // do something with the bytes read
} while(bytes_read);

[1] Notably, gcc's standard library implementation seems to always return something for std::filebuf but on MSVC, the first call will simply always return 0 bytes read :)

Upvotes: 1

Alexander
Alexander

Reputation: 758

as far as tcpip packet can be received to a number of smaller packets so I'd recommend to add some additional data to tcpip something like this:

  1. serialize you data to stream
  2. get size of stream
  3. send to tcpip buffer starting with size of stream and then data from the stream

receiver reads size and then reads the rest of the packet.

after you received the full packet - call deserialization

Upvotes: 2

Related Questions