C# 使用 grpc

來源:互聯網
上載者:User

孫廣東  2016.12.21

http://blog.csdn.NET/u010019717


GitHub: https://github.com/grpc/grpc

gRPC 官方文檔中文版  : http://doc.oschina.net/grpc?t=60132

 

             基於ProtoBuf(ProtocolBuffers)序列化協議開發,且支援眾多開發語言。gRPC提供了一種簡單的方法來精確地定義服務和為iOS、Android和後台支援服務自動產生可靠性很強的用戶端功能庫。用戶端充分利用進階流和連結功能,從而有助於節省頻寬、降低的TCP連結次數、節省CPU使用、和電池壽命。



        然後在當前解決方案下     添加兩個控制台應用程式 grpcServer 、grpcClient。

 

 

    前面說了, grpc基於 Protobuffer,  所以 定義服務

這裡我們在  grpcTest   項目裡添加一個 test.proto 內容如下:

 

下面主要定義一個gRPC  的  服務裡面有個 SayHello rpc 方法

 

syntax ="proto3";packagegrpcTesst; servicegRPC {  rpc SayHello (TestRequest) returns(TestReply) {}} messageTestRequest {  string name = 1;} messageTestReply {  string message = 1;}


 

  使用Grpc.Tools產生代碼

有了服務,開始產生代碼。

            首先需要添加引用:

在每個項目中添加上Grpc 及 Google.Protobuf 

切換項目簡單:



      NuGet 命令列(視圖-> 其他視窗 -> 封裝管理員控制台):

Install-Package Grpc

Install-Package Google.Protobuf

    

      然後在  grpcTest  項目中再添加上工具   Grpc.Tools(要產生源檔案)

Install-Package Grpc.Tools

              CMD命令列來到解決方案下目錄下(目錄為packages 的上層目錄)

 

 

 

然後輸入下列命令(你可以把  rpcTest  該成你項目的名字。): 


 


         packages\Grpc.Tools.1.0.0\tools\windows_x86\protoc.exe-IgrpcTest --csharp_out grpcTest  grpcTest\test.proto --grpc_out grpcTest --plugin=protoc-gen-grpc=packages\Grpc.Tools.1.0.0\tools\windows_x86\grpc_csharp_plugin.exe

 

跟  Protobuffer  類似啦~~~~

            執行完以後,在 grpcTest 目錄下會多出  Test.cs 及 TestGrpc.cs 類,將其包含至grpcTest  項目既可(  項目上右鍵-》 添加-》現有項    選擇檔案就行了)。

 

            然後          grpcServer、 grpcClient   分別都引用 grpcTest (  項目引用節點上   右鍵-》 添加引用-》 項目  解決方案  下 選擇項目    確定  就行了)。

  建立服務端及用戶端

下面我們來編寫服務端及用戶端

 

首先是服務端:

          將預設   Program.cs 檔案   按F2 重新命名 為 TestServer.cs  (註: 在 解決方案面板上操作,會提示 是否同時修改相關的引用,  選擇是。)

usingGrpc.Core;usingGrpcTesst;usingSystem;usingSystem.Threading.Tasks; namespacegrpcServer{    class gRPCImpl : gRPC.gRPCBase    {        // 實現SayHello方法        public override Task<TestReply>SayHello(TestRequest request, ServerCallContext context)        {            return Task.FromResult(newTestReply { Message = "Hello " + request.Name });        }    }     class TestServer    {        const int Port = 9007;         public static void Main(string[] args)        {            Server server = new Server            {                Services= { gRPC.BindService(new gRPCImpl()) },                Ports = { newServerPort("localhost", Port, ServerCredentials.Insecure) }            };            server.Start();             Console.WriteLine("gRPC serverlistening on port " + Port);           Console.WriteLine("任意鍵退出...");            Console.ReadKey();             server.ShutdownAsync().Wait();        }    }}


  

服務端需要實現SayHello方法。

 

然後是用戶端:

         將預設   Program.cs 檔案  按F2 重新命名 為  TestClient.cs   (註: 在 解決方案面板上操作,會提示 是否同時修改相關的引用,  選擇是。)

usingGrpc.Core;usingGrpcTesst;usingSystem; namespacegrpcClient{    class TestClient    {        static void Main(string[] args)        {            Channel channel = newChannel("127.0.0.1:9007", ChannelCredentials.Insecure);             var client = newgRPC.gRPCClient(channel);            var reply = client.SayHello(newTestRequest { Name = "sunguangdong" });           Console.WriteLine("來自" +reply.Message);             channel.ShutdownAsync().Wait();           Console.WriteLine("任意鍵退出...");            Console.ReadKey();        }    }}


 

 

在這兩個項目上右鍵    產生。

           分別到對應的目錄執行,首先啟動grpcServer.exe,然後執行grpcClient.exe。

 

 

 

 

           成功進行通訊了,實現了gRPC。

它們之間的  通訊使用Grpc.Core中的   Services    和  Channel    來通訊。

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.