缓冲区的关键是: 字符串数据 和 类型数据 之间的相互转换。比如将char *的数据的按1byte 1 byte的读入转化为bool、char、uint8、int16、uint16、int32(相当于int),uint32、int64(相当于long long);当然还有double。
网络缓冲区分为发送端 和 接收端。发送端将类型数据 转换为 字符串数据。 接收端将字符数据 转换为 类型数据。
一、发送端
#ifndef SMPEnplexer_H
#define SMPEnplexer_H
#include "SMP_COMMAND.h"
class SMPEnplexer
{
public:
SMPEnplexer(unsigned bufsize=8192); //default is 8KB
~SMPEnplexer();
char* data() {return _data;};
unsigned length() {return _pos;};
void setLength(int pos){_pos += pos;};
void setBufferSize(int size);
unsigned buffersize(){return _bufSize;};
void reset();
void addHead();
// add a argument
void addBoolArg(bool value);
void addCharArg(char value);
void addUInt8Arg(unsigned char value);
void addInt16Arg(short value);
void addUInt16Arg(short value) { addInt16Arg(value); };
void addInt32Arg(int value);
void addUInt32Arg(unsigned value) { addInt32Arg(value); };
void addInt64Arg(long long int value);
void addUInt64Arg(long long unsigned value) { addInt64Arg(value); };
void addFloatArg(float value);
void addStringArg(const QString &value);
void addCharArray(char* str,int len);
PACKAGE_HEAD head;
protected:
unsigned _bufSize;
char *_data;
unsigned _pos;
QTextCodec* codec;
};
#endif // SMPEnplexer_H
二、接收端
接收端将字符串数据流 转换为 相应的类型数据。
#ifndef SMPDeplexer_H
#define SMPDeplexer_H
#include
#include "SMP_COMMAND.h"
class SMPDeplexer
{
public:
SMPDeplexer(unsigned bufSize = 4096);
~SMPDeplexer();
char *data() {return _data;}
unsigned length() {return _length;}
void setLength(int len) {_length = len;}
unsigned buffersize() {return _bufSize;}
void setBufferSize(unsigned size);
void reset();
// demultiplex the next arg in the stream
bool boolArg();
char charArg();
unsigned char uint8Arg();
short int16Arg();
unsigned short uint16Arg() { return int16Arg(); }
int int32Arg();
unsigned uint32Arg() { return int32Arg(); }
long long int int64Arg();
long long unsigned uint64Arg() { return int64Arg(); }
void deplexHead();
void deplexCharArray(char* str,int len);
char *_data;
unsigned _pos;
unsigned _bufSize;
unsigned _length;
QTextCodec* codec;
PACKAGE_HEAD head;
};
#endif // SMPDeplexer_H