C# ProtoBuf 入門


個人理解:protobuf 就是一種傳輸數據的協議,或者說格式,跟json類似。

首先羅列下需要的工具:

VS2015
protobuf-csharp-port-master 下載地址:https://github.com/jskeet/protobuf-csharp-port
(備注:有另一種工具protobuf-net使用起來更方便,有興趣的可以參考這篇文章:http://www.cnblogs.com/jhli/p/6139914.html)

首先,將下載好的 protobuf-csharp-port-master 工具解壓縮,進入build文件夾

點擊BuildAll.bat,會在子文件夾下自動生成 build_output 和 build_temp 兩個新文件夾

新建一個test.proto文件

package ProtoTest;

message Person {
  required string name = 1;
  required int32 id = 2;        // Unique ID number for this person.
  optional string email = 3;
 
  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }
 
  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }
 
  repeated PhoneNumber phone = 4;
}

 將其放入 build_output 的 tools 文件夾下

運行命令 protoc --descriptor_set_out=test.protobin --include_imports test.proto 會在文件夾下面新生成一個 test.protobin 文件

再運行 protogen test.protobin 就可以生成 test.cs 文件了

此時就可以將cs文件直接添加到項目中使用了

舉個例子:

新建一個webservice項目

添加方法

[WebMethod]
        public byte[] Test()
        {
            return new Person.Builder().SetId(1).SetName("王尼瑪").SetEmail("woshiwangnima@qq.com").Build().ToByteArray();
        }

在另一個項目中調用這個方法

ProtoServiceSoapClient service = new ProtoServiceSoapClient();

            var test = service.Test();

            ProtoTest.Person person = ProtoTest.Person.ParseFrom(test);

可以看到這個數據已經傳輸到調用方來了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM