Server 在Ubuntu V20.04; Client 在Windows CMD运行。
- PowerShell Core v7.2
- IDE: VS2022 Community(v17.0)/VS Code(docker extension)
- VM: VBox(v6.1)
接口文件说明
Protos/greet.proto
定义service
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
定义message
- request
message HelloRequest {
string name = 1;
}
- response
message HelloReply {
string message = 1;
}
server
Create
VS2022
注意:服务器需要docker支持!
VS code
dotnet new grpc -o GreeterServer
add docke file
- View -> Command Palette(Ctrl+Shift+P)
- Enter: Docker fi
- choice1: Add Docker Files to Workspace…
- choice2: .NET: ASP.NET Core
- choice3: Linux
- Enter: 80
- choice4: No(Include compose file)
实现的service
VS2022/vs code自动生成
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
return Task.FromResult(new HelloReply
{
Message = "Hello " + request.Name
});
}
添加SSL支持1
Program.cs
configure WebHost4:
builder.WebHost.ConfigureKestrel(options =>
{
options.Listen(IPAddress.Any, 5001, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http2;
});
});
client
建一个Console应用程序,来测试gRPC服务。
Create
vs2022
主要的NuGet:
Install-Package Grpc.Core" -Version 2.41.1
其他NuGet:
Install-Package Google.Protobuf -Version 3.19.1
Install-Package Grpc.Net.Client -Version 2.40.0
Install-Package Grpc.Tools -Version 2.41.1
vs code
dotnet new console -o GreeterClient
NuGet
dotnet add GreeterClient.csproj package Grpc.Net.Client
dotnet add GreeterClient.csproj package Google.Protobuf
dotnet add GreeterClient.csproj package Grpc.Tools
增加Proto2
GreeterClient.csproj
<ItemGroup>
<Protobuf Include="Protos\greet.proto" GrpcServices="Client" />
</ItemGroup>
test程序3
Program.cs
注意:需先build生成gRPC stub类
static async Task Main(string[] args)
{
// The port number(5001) must match the port of the gRPC server.
using var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new Greeter.GreeterClient(channel);
var reply = await client.SayHelloAsync(
new HelloRequest { Name = "GreeterClient" });
Console.WriteLine("Greeting: " + reply.Message);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
Test picture