syntax ="proto3"; package RouteGrpc; service HelloWorld{ rpc SayHello(HellowRequest)returns (ReturnsString){} } message HellowRequest{ string Title=1; string Content=2; } message ReturnsString{ string Content=1; }
tools\protoc.exe -I protos --csharp_out out HelloGrpc.proto --plugin=protoc-gen-grpc=tools\grpc_csharp_plugin.exe //-I 工做目錄 // --grpc_out 第一個參數是表示輸出文件目錄 第二個參數表示 描述文件名稱(protobuf文件) // --csharp_out 和grpc_out 參數相同 //--plugin= 表示輸出c#的插件 tools\protoc.exe -I protos --grpc_out outgrpc HelloGrpc.proto --plugin=protoc-gen-grpc=tools\grpc_csharp_plugin.exe //服務相關
public class HelloService:HelloWorld.HelloWorldBase { public override Task<ReturnsString> SayHello(HellowRequest request, ServerCallContext context) { return Task.FromResult(new ReturnsString { Content = "Hello " + request.Title +"端口9007"}); } }
namespace Service { class Program { const int Port = 9007; static void Main(string[] args) { Server server = new Server { Services = { HelloWorld.BindService(new HelloService()) }, Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) } }; server.Start(); Console.WriteLine("RouteGuide server listening on port " + Port); Console.WriteLine("Press any key to stop the server..."); Console.ReadKey(); server.ShutdownAsync().Wait(); } } }
namespace Client { class Program { static void Main(string[] args) { Channel channel = new Channel("127.0.0.1:9007", ChannelCredentials.Insecure); var client = new HelloWorld.HelloWorldClient(channel); var retrunstr = client.SayHello(new HellowRequest() { Title = "this is message", Content = "this is content" }); //var retrunstr = await client.SayHelloAsync(new HellowRequest() { Title = "this is message", Content = "this is content" }); Console.WriteLine("來自" + retrunstr.Content); channel.ShutdownAsync().Wait(); Console.WriteLine("任意鍵退出..."); Console.ReadKey(); } } }