我的理解:protobuf 就是一種傳輸數據的協議,或者說格式,跟json相似。html
首先羅列下須要的工具:git
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文件夾github
點擊BuildAll.bat,會在子文件夾下自動生成 build_output 和 build_temp 兩個新文件夾web
新建一個test.proto文件json
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 文件ui
再運行 protogen test.protobin 就能夠生成 test.cs 文件了this
此時就能夠將cs文件直接添加到項目中使用了spa
舉個例子:code
新建一個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);
能夠看到這個數據已經傳輸到調用方來了