1.结构化数据的传输
- 通信双方在进行网络通信时:
- 如果需要传输的数据是一个字符串,那么直接将这一个字符串发送到网络中,此时对端也能中网络当中获取到这个字符串
- 但如果需要传输的是一些结构化的数据,此时就不能将这些数据一个个发送到网络中(也可以发,但一般不会这样做)
- 协议是一种约定。socket api的接口,在读写数据时, 都是按"字符串"的方式来发送接收的,如果要传输一些"结构化的数据"怎么办呢?
- 需要对结构化的数据进行打包(序列化),通过网络发送至对端主机,再进行解包(反序列化)
2.序列化与反序列化
- 序列化:将结构化的数据转换为字节序列发送到网络
- **反序列化:**将网络中的字节序列转化为结构化的数据
- 序列化与反序列化有何好处?
- 结构化的数据不便于网络传输
- 序列化为应用层网络通信提供方便
- 反序列化为了方便上层使用数据
- 序列化和反序列化本质就是将应用和网络进行了解耦
- 可通过以下代码感受序列化反序列化
class Request
{
public:
Request()
{}
Request(int x, int y, int op)
: _x(x), _y(y), _op(op)
{}
~Request()
{}
std::string Serialize()
{
std::string str;
str = std::to_string(_x);
str += SPACE;
str += _op;
str += SPACE;
str += std::to_string(_y);
return str;
}
bool DeSerialize(const std::string &str)
{
size_t left = str.find(SPACE);
if(left == std::string::npos)
{
return false;
}
size_t right = str.rfind(SPACE);
if (right == std::string::npos)
{
return false;
}
_x = atoi(str.substr(0, left).c_str());
_y = atoi(str.substr(right + SPACE_LEN).c_str());
if(left + SPACE_LEN < str.size())
{
_op = str[left + SPACE_LEN];
return true;
}
else
{
return false;
}
}
public:
int _x;
int _y;
char _op;
};
class Response
{
public:
Response()
{}
Response(int ret, int code)
: _code(code)
, _ret(ret)
{}
~Response()
{}
std::string Serialize()
{
std::string str = std::to_string(_code);
str += SPACE;
str += std::to_string(_ret);
return str;
}
bool DeSerialize(std::string &str)
{
size_t pos = str.find(SPACE);
if(pos == std::string::npos)
{
return false;
}
_code = atoi(str.substr(0, pos).c_str());
_ret = atoi(str.substr(pos + SPACE_LEN).c_str());
return true;
}
public:
int _ret;
int _code;
};
3.json序列化和反序列化
- **注意:**json库为第三方库,需要额外安装
- json序列化/反序列化是一个成熟的方案,可通过以下代码对比一下json和自己定制序列化协议的区别
class Request
{
public:
Request()
{}
Request(int x, int y, int op)
: _x(x), _y(y), _op(op)
{}
~Request()
{}
std::string Serialize()
{
Json::Value root;
root["x"] = _x;
root["y"] = _y;
root["op"] = _op;
Json::FastWriter writer;
return writer.write(root);
}
bool DeSerialize(const std::string &str)
{
Json::Value root;
Json::Reader reader;
reader.parse(str, root);
_x = root["x"].asInt();
_y = root["y"].asInt();
_op = root["op"].asInt();
return true;
}
public:
int _x;
int _y;
char _op;
};
class Response
{
public:
Response()
{}
Response(int ret, int code)
: _code(code)
, _ret(ret)
{}
~Response()
{}
std::string Serialize()
{
Json::Value root;
root["code"] = _code;
root["result"] = _ret;
Json::FastWriter writer;
return writer.write(root);
}
bool DeSerialize(std::string &str)
{
Json::Value root;
Json::Reader reader;
reader.parse(str, root);
_code = root["code"].asInt();
_ret = root["result"].asInt();
return true;
}
public:
int _ret;
int _code;
};