0

I want to transfer data from a client to a server. The data is stored in a Data:

class Data{
     Type1 Obj1;
     Type2 Obj2;
     Type3 Obj3;
     //...
}

First I insert the data into a buffer type:

Buffer(data);

Then I use one of Boost.Asio's send functions:

Send(endpoint_s, buffer_1)

Alternatively, I could send Data directly:

Send(endpoint_s, &data, sizeof(Data));

On the receiving end, I am expecting a Data. First I receive the data into a Buffer.

Receive(endpoint_c, buffer_2);

Now buffer_2 contains a collection of bits that represents a Data on the server's machine. I wish I could just reinterpret_cast these bits into a Data, however, this results in undefined behavior. How am I supposed to convert the collection of bits in buffer_2 into a Data in a way that does not result in undefined behavior?

Mark Wallace
  • 528
  • 2
  • 12
  • 4
    Search for "serialization" and you'll probably find a lot of information, like [this one](https://isocpp.org/wiki/faq/serialization) – Ted Lyngmo Aug 01 '22 at 17:20
  • 1
    Best not to send raw bit, rather a serialised message created by you. There are also libraries that do this eg [Protocol Buffers from Google](https://developers.google.com/protocol-buffers) – Richard Critten Aug 01 '22 at 17:21
  • 1
    This networking programming guide on Network Byte Order might be useful: https://beej.us/guide/bgnet/html/#byte-order – ajoseps Aug 01 '22 at 17:22
  • 2
    The short answer is: "Don't do that." Define a format for the data on the wire. The server needs to convert its data to that format, and the client needs to parse that format. Most other methods are short trips into madness. – Jerry Coffin Aug 01 '22 at 17:23
  • Ah, thanks guys. It seems then that ```char```s are guaranteed to have a specific bit representation? – Mark Wallace Aug 01 '22 at 17:30

0 Answers0