【技术类】PB兼容问题

如果一端更新了协议,那么另一端接收到消息还能解析吗?

一、不仅增加了字段,而且还更改了原有字段顺序

#include <iostream>
#include <string>
#include "Old.pb.h"
#include "New.pb.h"
using namespace std;

int main()
{
//new proto
/*
	syntax = "proto2";
	package My;
	message Test
	{
		required int32 first  = 1;
		optional int32 second = 2;
		optional string fourth = 3;	
		optional int32 third  = 4;
	}
*/
	res = accept();
	My::Test st;
	st.set_first(10);
	st.set_second(20);
	st.set_third(30);
	st.set_fourth(40);
	
	string str;
	if(!st.SerializeToString(&str))
		cout<<"Serlialize Error"<<endl;
	send(res,str.c_str(),64,0);
//old proto
/*
	syntax = "proto2";
	package My;
	message Test
	{
		required int32 first  = 1;
		optional int32 second = 2;
		optional int32  third = 3;
	}
	
*/
char buffer[64] = {0};
recv(sockfd,buffer,64,0);

My::Test st;
if(st.ParseFromString(buffer))
	cout<<st.first()<<" "<<st.second()<<" "<<st.third()<<endl;
else
	cout<<"ParseFrom Error"<<endl;
	
结果有点意思,10 20 0,也就是后面被打乱的字段解析不出来,那么该字段就为默认值。

二、增加字段,不修改原有字段顺序

//new proto
/*
	syntax = "proto2";
	package My;
	message Test
	{
		required int32 first  = 1;
		optional int32 second = 2;
		optional int32 third  = 3;	
		optional int32 fourth = 4;
	}
*/	
	My::Test st;
	st.set_first(10);
	st.set_second(20);
	st.set_third(30);
	st.set_fourth(40);
	
	string str;
	if(!st.SerializeToString(&str))
		cout<<"Serlialize Error"<<endl;
	send(res,str.c_str(),64,0);
	
	接受方代码不用变动,结果10 20 30,可以正确解析,并不会ERROR,新字段当然没法认识。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值