开发者

Encapsulation of data (Network programming)

开发者 https://www.devze.com 2023-02-20 12:37 出处:网络
I have read BG\'s Introduction to Network Programming but one topic stands still as questionable: Data encapsulation.

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 variable开发者_Go百科s 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?


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.


Send() takes a char* to allow to send any binary data in multiples of one byte. Have you tried casting to a char*?

At the receive end you do then have to unpack the first few bytes to discover the length. Of course this approach assumes that sender and receiver use the same length ints. You should also me careful about the packing arguments you send to the compiler.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号