要建立 gRPC 的 Client,須先將 GRPC.Tools、GRPC.Core、Google.Protobuf 這三個 NuGet 套件加入參考。

...

...

然後設定從 Proto 檔產生需要的程式部分。

1.png

編譯後可在 obj 下看到產出的檔案。

2.png

接著開始實作 Client。

然後帶入 Server 位置建立 Channel 物件。

...
var channel = new Channel($"{host}:{port}", ChannelCredentials.Insecure);
...

接著帶入 Channel 建立 Service 的 Client 物件。

...
var client = new HelloService.HelloServiceClient(channel);
...

透過 Service 的 Client 物件調用對應的方法。

...
Console.WriteLine(client.SayHello(new HelloRequest()
{
...
}));
...

最後在不使用時將 Channel 關閉即可。

...
channel.ShutdownAsync();
...

程式寫起來會像下面這樣:

using System;
using Grpc.Core;
using GRPC.Message;

namespace GRPC.Client
{
class Program
{
static void Main(string[] args)
{
var channel = new Channel("127.0.0.1:8888", ChannelCredentials.Insecure);
var client = new HelloService.HelloServiceClient(channel);

Console.WriteLine(client.SayHello(new HelloRequest()
{
Name = "Larry"
}));

channel.ShutdownAsync().Wait();
}
}
}

運行起來 Client 就會透過 rpc 去跟 Server 調用,並將訊息回傳。

3.png