宝安品牌网站制作江苏外协机械加工网
news/
2025/10/9 1:26:34/
文章来源:
宝安品牌网站制作,江苏外协机械加工网,聊城专业做网站公司,全球做空现货黄金的网站介绍
上一节中#xff0c;我们介绍了protobuf#xff0c;简单来说#xff0c;它是一种消息数据格式#xff0c;其作用类似于json#xff0c;但是比json的使用效率要高。
除此以外#xff0c;我们介绍了protobuf的简单使用#xff0c;也就是如何可以像使用json一样我们介绍了protobuf简单来说它是一种消息数据格式其作用类似于json但是比json的使用效率要高。
除此以外我们介绍了protobuf的简单使用也就是如何可以像使用json一样将消息数据进行序列化和反序列化
nullhttps://blog.csdn.net/qq_58158950/article/details/136277730?spm1001.2014.3001.5501但是在日常开发中除了我们在上节中会使用到的普通数据之外我们还会用到列表数组类型和映射表类型的数据本节我们将介绍如何使用protobuf对列表类型的数据进行序列化和反序列化
使用
protobuf中的代码复用
仍旧首先编写protobuf配置文件
在上一节中我们定义登录响应消息类型的时候有两个成员变量errcode和errmasg这两个成员变量的作用就是来告诉客户端我们发送给服务端的请求是否出错以及出错信息。
message loginResponse
{int32 errcode1;string errmsg2;bool success3;
}
因此作为响应消息这两个成员变量是必须的比如我们如果要定义一个注册请求消息
message regResponse
{int32 errcode1;string errmsg2;bool success3;
}
显然这种定义方式不符合代码的复用因此我们完全可以将这两个成员变量单独拿出来定义一个类型
//封装响应消息
message resultCode
{int32 errcode1;bytes errmsg2;
}
那么登录响应消息就变成了
//登录响应消息
message loginResponse
{resultCode resMsg1;bool success3;
}
而在c代码中我们想要使用loginResponse类的resultCode 成员变量时就需要这样写
void test()
{loginResponse reqb;//获取resultCode成员对象的指针然后再通过该指针设置成员变量//该指针的获取方法是mutable_成员变量名称resultCode*rc reqb.mutable_resmsg();rc-set_errcode(1);rc-set_errmsg(登录处理失效);
}
protobuf中的列表数据类型
接下来我们介绍protobuf中列表数据类型
我们继上述配置文件代码再定义一个user消息类型其中性别成员变量是一个枚举类型
//用户消息
message user
{bytes name1;uint32 age2;enum sex{man0;woman1;}
}
我们再定义一个好友列表请求和好友列表响应消息
//好友列表请求
message friendListReq
{int32 userid1;
}//好友列表请求响应
message friendListResponse
{resultCode resMsg1;// repeated关键字表示该消息是一个列表而不是单个消息repeated user friendList2;
}由于好友列表响应返回的消息中好友不会只有一个因此需要返回一个user列表数组我们使用repeated关键字进行说明
完整的protobuf配置文件如下
syntaxproto3;//声明protobuf版本
package rpcProto;//声明了代码所在的命名空间//定义登录请求消息类型
message loginRequest
{bytes name1;//表示loginRequest消息的第一个字段bytes passwd2;//表示loginRequest消息的第二个字段
}//封装响应消息
message resultCode
{int32 errcode1;bytes errmsg2;
}//登录响应消息
message loginResponse
{resultCode resMsg1;bool success3;
}//用户消息
message User
{bytes name1;uint32 age2;enum Sex{man0;woman1;}Sex sex3;
}//好友列表请求
message friendListReq
{int32 userid1;
}//好友列表请求响应
message friendListResponse
{resultCode resMsg1;// repeated关键字表示该消息是一个列表而不是单个消息repeated User friendList2;
}在终端输入以下代码生成对应的类文件
protoc test.proto --cpp_out./
在c代码中测试
#includeiostream
#includestring
#includetest.pb.h
using namespace std;
using namespace rpcProto;void test()
{friendListResponse fres;resultCode* pcfres.mutable_resmsg();pc-set_errcode(0);pc-set_errmsg(请求无错);// 使用add_列表变量名获取列表消息指针User *user1fres.add_friendlist();user1-set_name(zhangsan);user1-set_age(20);user1-set_sex(User::man);User *user2fres.add_friendlist();user2-set_name(lisi);user2-set_age(22);user2-set_sex(User::woman);coutfres.friendlist_size()endl;}int main()
{test();return 0;
}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/932115.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!