前面服务端已经建立了,我们要建立客户端去调用它。
环境
Visual Studio 2022
.NET Core 6.0
一、创建项目
创建一个“ASP.NET Core 空”的项目。
二、添加 NuGet 程序包
Grpc.Net.Client
Google.Protobuf
Grpc.Tools
三、添加协议缓冲区文件
把 Server 那边的 .proto 文件复制过来即可。
四、工程文件中加上 Protobuf
点击项目,会自动打开 *.csproj,加上一句:
<ItemGroup> <Protobuf Include="Greeter.proto" GrpcServices="Client" /> </ItemGroup>
GrpcServices 的 Server 变成了 Client。
五、改 Program.cs
using Grpc.Net.Client; using Itpow; using var channel = GrpcChannel.ForAddress("https://localhost:7199"); // 注意端口。 var client = new Greeter.GreeterClient(channel); var reply = await client.SayHelloAsync(new HelloRequest { Name = "itpow" }); Console.WriteLine("Greeting: " + reply.Message); Console.WriteLine("Press any key to exit..."); Console.ReadKey();
同样我们并没有写 GreeterClient、SayHelloAsync,Message 我们写的也是小写,这些都编译的结果。
六、运行
Ctrl + F5,运行效果如下:
相关阅读