netcore 實現一個簡單的Grpc 服務端和客戶端

  • 參考資料,和詳細背景不作贅述。
  • 首先定義prop 文件
    syntax  ="proto3";
    package RouteGrpc;
    service HelloWorld{
    rpc  SayHello(HellowRequest)returns (ReturnsString){}
    }
    message  HellowRequest{
    string Title=1;
    string Content=2;
    }
    
    message  ReturnsString{
    string Content=1;
    }
  • 而後根據prop文件生成對應的客戶端和服務端的代碼(這裏要提早準備protoc.exe和grpc_csharp_plugin.exe)
    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   //服務相關
  • 生成以後服務端實現Sayhellow相關方法
     public class HelloService:HelloWorld.HelloWorldBase
        {
            public override Task<ReturnsString> SayHello(HellowRequest request, ServerCallContext context)
            {
                return Task.FromResult(new ReturnsString { Content = "Hello " + request.Title +"端口9007"});
            }
        }
  • 最終客戶端和服務端代碼(一共有四種RPC 這裏只實現最簡單的那種其它相似)
    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();
            }
        }
    }

     

  • 項目結構

相關文章
相關標籤/搜索