How to use Google's protocol-buffer


protocbuf introduction


Protocol-buffer is a Technic of Google( aplhabet corp.) , which is used to interchange data on network. Protocol-buffer has its own syntax and compiler and compact serialized output format. More details about encoding is as following:

Encoding


official intro

Source code


Protocol-buffer

Building


Example


Text

  • regreq.txt
  • head{ magic:0xaabbccdd len:8 version:1 reserved:0 }
    body{ name:"harrywu" age:22 }

    Protoc-Buffer
  • regreq.proto
  • package com.example.register
    
    message Head{
        required uint32 magic   = 5;
        required uint32 len     = 6;
        required uint32 version = 7;
        required uint32 reserved= 8;
    }
    
    message Body{
        required uint32 age  = 3;
        required string name = 4;
    }
    
    message RegisterRequest
    {
        required Head head = 1;
        required Body body = 2;
    }

    encode

    protoc --encode=com.example.regisger.RegisterRequest ./regreq.proto < regreq.txt >regreq.bin

    decode

    protoc --decode=com.example.register.RegisterRequest ./regreq.proto <regreq.bin >regreq.txt