前些天發布gRPC C# 學習,在.NET Framework 中使用gRPC ,今天來學習 .NET Core gRPC。
gRPC 的.NET Core 包在NuGet 上發布了,結合.NET Core 實現gRPC 完美跨平台。
本篇主要講解 .NET Core 版gRPC客戶端運行在Ubuntu系統上,與局域網內的服務端通信。
下面我們來正式開始。
在之前的代碼基礎開發.NET Core版。
本文運行環境:
服務端:WIN10 x64
客戶端:Ubuntu 14.04
添加.NET Core版gRPC Client
首先我們打開之前的gRPCDemo 代碼,GitHub:https://github.com/linezero/Blog/tree/master/gRPCDemo 。
添加一個.NET Core 控制台應用 gRPCNETCoreClient

然后在 gRPCNETCoreClient 項目上添加引用:
Install-Package Grpc -Pre
移植傳統類庫至.NET Core類庫
安裝好Grpc 以后我們就可以來移植類庫了,這里我們首先創建一個gRPCNETCoreDemo Class Library。

新建好以后我們將 project.json 文件更改為如下:
{ "version": "1.0.0-*", "frameworks": { "net452": { "dependencies": { "Grpc": "1.0.0", "Grpc.Core": "1.0.0", "Google.Protobuf": "3.0.0", "System.Interactive.Async": "3.0.0" } }, "netstandard1.6": { "imports": "dnxcore50", "dependencies": { "NETStandard.Library": "1.6.0", "Grpc": "1.0.1-pre1", "Grpc.Core": "1.0.1-pre1", "Google.Protobuf": "3.1.0", "System.Interactive.Async": "3.1.0-rc" } } } }
這樣類庫就能支持.NET Framework 4.5.2 以及 .NET Core。
這里我省略了生成代碼,直接將gRPCDemo 中的類復制過來。然后gRPCNETCoreClient 添加gRPCNETCoreDemo 引用。
gRPCNETCoreClient 中Program.cs 添加如下代碼,基本上和上篇代碼一致,新增了控制台編碼輸出格式。
public class Program { public static void Main(string[] args) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Channel channel = new Channel("127.0.0.1:9007", ChannelCredentials.Insecure); var client = new gRPC.gRPCClient(channel); var reply = client.SayHello(new HelloRequest { Name = "LineZero .NET Core Client" }); Console.WriteLine("來自" + reply.Message); channel.ShutdownAsync().Wait(); Console.WriteLine("任意鍵退出..."); Console.ReadKey(); } }
代碼編寫好以后,我們來執行gRPCServer ,然后使用dotnet run 執行 gRPCNETCoreClient。

成功通信,證明支持.NET Core。
發布至Ubuntu系統運行
下面將gRPCNETCoreClient 發布至Ubuntu系統跨平台運行。
代碼綁定ip需要稍作調整。
查看本地ip 是多少,將gRPCServer 中的localhost 改成本地ip ,並將 Client的127.0.0.1 也改成本地ip。
發布 gRPCNETCoreClient
dotnet publish
將發布后的目錄復制到 Ubuntu 系統。
下面先在本地啟動Server ,然后在Ubuntu系統執行Client 。

成功在Ubuntu 系統上通信,這里服務端是運行在本地,客戶端是在另外一台機器上。
gRPC 官網文檔:http://www.grpc.io/docs/
protobuf文檔:https://developers.google.com/protocol-buffers/docs/overview
如果你覺得本文對你有幫助,請點擊“推薦”,謝謝。
