深度优先

这个家伙好懒,除了文章什么都没留下

0%

【.Net】在.Net Framework中使用gRPC

原文地址:https://iter01.com/537518.html

随着.Net Core 3.0及版本版本的出现,微软似乎正在完成一个Windows特征的WCF。作为WCF的备选者,VS Code或VS2019已经有了基于.Net Core 3.0平台的“gPRC专案模板”。极大地简化了gRPC的开发过程。

gRPC也可深入.Net Framework。由于VS2019没有提供基于.Net Framework平台的“gPRC专案模板”,开发者需要用手工方式处理。本文采用VS2019,以.Net Framework 4.7.2为例,描述gPRC的实现步骤。

步骤一、建立解决方案及专案

  1. Greeter,.Net Framework4.7.2类库专案,定义服务器与客户端之间的服务协议
  2. GreeterServer,.Net Framework4.7.2 证书程序,gRPC服务端,提供gPRC服务
  3. GreeterClinet,.Net Framework4.7.2 调试程序,gRPC客户端,呼叫GreetServer提供的服务

步骤二、NuGet获取程序包

  1. 在“解决方案gRPCDemo”中滑鼠,“管理解决方案的NuGet程序包”

  1. 安装“Google.ProtoBuf”

  1. 安装“Grpc.Core”

  1. 安装“Grpc.Tools”

步骤三、此写服务协议并生成服务类(步骤需手工处理)

  1. 在类库专案“Greeter”中新增“helloworld.proto”档案,输入以下服务定义。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
syntax = "proto3";

package Greeter;

service Greet {
rpc SayHello (HelloRequest) returns (HelloReply);
}

message HelloRequest {
string name = 1;
}

message HelloReply {
string message = 1;
}
  1. 生成服务类

在“解决方案”上点选滑鼠方案,“在档案资源管理中开启资料夹”

输入以下命令,将“hello.proto”转换为服务类

1
packagesGrpc.Tools.2.32.0toolswindows_x86protoc.exe -I Greeter --csharp_out Greeter Greeterhello.proto --grpc_out Greeter --plugin=protoc-gen-grpc=packagesGrpc.Tools.2.32.0toolswindows_x86grpc_csharp_plugin.exe

  1. 将生成的服务类Hello.cs和HelloGrpc.cs新增到“Greeter”专案中

  1. 编译类库“Greeter”

步骤四、写服务端

  1. 新增类库专案引援

  2. 服务端程序码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using Greeter;
using Grpc.Core;
using System;
using System.Threading.Tasks;

namespace GreeterServer
{
class Program
{
static void Main(string[] args)
{
const int port = 5555;
Server server = new Server
{
Services = { Greet.BindService(new GreetImpl()) },
Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
};
server.Start();

Console.WriteLine($"Greeter Server Listening on port {port}");
Console.WriteLine("Press Enter to exit");
Console.ReadLine();

server.ShutdownAsync().Wait();

}
}

class GreetImpl: Greet.GreetBase
{
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
return Task.FromResult(new HelloReply { Message = $"Hello {request.Name}" });
}
}

}

步骤五、写客户端程序码

  1. 新增类库专案引援

  2. 客户端程序码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using Greeter;
using Grpc.Core;
using System;

namespace GreeterClient
{
class Program
{
static void Main(string[] args)
{
Channel channel = new Channel("127.0.0.1:5555", ChannelCredentials.Insecure);
var client = new Greet.GreetClient(channel);
var replay = client.SayHello(new HelloRequest { Name = "Auto" });
Console.WriteLine($"{replay.Message}");

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

执行结果