如果一端更新了协议,那么另一端接收到消息还能解析吗?
一、不仅增加了字段,而且还更改了原有字段顺序
#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,新字段当然没法认识。