稍微复杂点的protobuf 嵌套消息使用

//protoc -I=./ --cpp_out=./ ./chat.proto 
syntax = "proto2";
package chat;

// 通知消息的后缀用Ntc,请求消息Req,响应消息Res
enum MSG
{
    //注册
    Register_Req	=	101;
    Register_Res	=	201;
    
    //登录
	Login_Req	=	102;
    Login_Res	=	202;
    
    //群聊
    Chat_public_Req = 103;
    Chat_public_Ntc = 203;

    //私聊
    Chat_private_Req = 104;
    Chat_private_Res = 204;

    //登出
    Logout_Req = 105;
}
message RegisterRequest
{
	required string username = 1;
	required string password = 2;
}

message RegisterResponse
{
    required int32 ttl = 1;
    optional string comment = 2;
}

message LoginRequest
{
	required string username = 1;
	required string password = 2;
}

message LoginResponse
{
    required int32 ttl = 1;
    optional string comment = 2;
}

message Chat_public_Request
{
    required string username  = 1;
    required string chat_data = 2;
}
message Chat_public_Response
{
    required string username  = 1;
    required string chat_data = 2;
}
message Chat_private_Request
{
    required string destuser_name = 1;
    required string username = 2;
    required string chat_data = 3;
}
message Chat_private_Response
{
    required string username = 1;
    required string chat_data = 2;
}

message QUIT
{
    required string username = 1;
}

message Request{
    optional RegisterRequest reg_req = 1;
    optional LoginRequest log_req = 2;
    optional Chat_public_Request chat_pu_req =3;
    optional Chat_private_Request chat_pr_req =4;
    optional QUIT quit = 5;
}
message Response{
    optional RegisterResponse reg_res = 1;
    optional LoginResponse log_res = 2;
    optional Chat_public_Response chat_pu_res =3;
    optional Chat_private_Response chat_pr_res =4;
}
message Message
{
    required MSG msg_type = 1;
    required int32 mid = 2;//自己的编号
    
    optional Request request = 3;
    optional Response response = 4;
}

void set2(){

    chat::Message msg;
    msg.set_msg_type(chat::MSG::Register_Req);

    chat::Request *req = new chat::Request;

    chat::RegisterRequest *regreq = new chat::RegisterRequest;
    regreq->set_username("qwe");
    regreq->set_password("123");

    req->set_allocated_reg_req(regreq);

    msg.set_mid(1);
    msg.set_allocated_request(req);

    len = msg.ByteSizeLong();
    printf("len=%ld\n",len);
    msg.SerializeToArray(buf, len);//序列化,obj成员保存在buf中
}

void get2(){
    chat::Message msg;
    msg.ParseFromArray(buf, len);

    cout<<msg.msg_type()<<endl;
    cout<<msg.mid()<<endl;
    cout<<msg.request().reg_req().username()<<endl;
    cout<<msg.request().reg_req().password()<<endl;
}

你可能感兴趣的:(protobuf)