Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encapsulation of data (Network programming)

I have read BG's Introduction to Network Programming but one topic stands still as questionable: Data encapsulation.
Basically I create a structure which contains data length, and a message. For example:

struct Data
{  
    int length;  
    std::string message;  
}

How can I send it? With the send() function, I can only send variables of char* type.
Also, when I send it, at the server side, should I create a dynamic buffer of length specified by the encapsulation and pack the message into it?

like image 672
adada Avatar asked Nov 05 '22 00:11

adada


1 Answers

The common approach in C++ is to provide functions which can serialize your custom type into either a 'stream' object, and then provide a way to get a pointer to the start of the data block which was accumulated in the stream.

A simple example of this is std::ostringstream which you can use to serialize data into a stream and then get a pointer to the constructed string:

int i = 13;
std::string message = "Hi";
std::ostringstream stream;
stream << i << message;

cout << stream.str() << endl; // prints "13Hi";

You could do the same for your Data type by providing appropriate overloads of the << and >> operator, as in:

std::ostringstream &operator<<( std::ostringstream &stream, const Data &v ) {
  return stream << v.length << v.message;
}

std::ostringstream &operator>>( std::ostringstream &stream, Data &v ) {
  return stream >> v.length; >> v.message;
}

Using these functions, you could do this:

Data myData = { 13, "Hello" };

std::ostringstream stream;
stream << myData;

const std::string serializedData = stream.str();
send( .., serializedData.c_str(), serializedData.size() + 1, .. );

On the receiving size, you could read the data into a buffer and then use an std::istringstream object to extract the data again:

const char receivedData[ 1024 ];
// fill receivedData array using recv()

std::string s = receivedData;
std::istringstream stream( s );
Data myData;
stream >> myData;

You might need to buffer the received data a bit until reading from the stream succeeds.

like image 125
Frerich Raabe Avatar answered Nov 09 '22 06:11

Frerich Raabe