我的理解: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);
能够看到这个数据已经传输到调用方来了