服务端:
1,通过vs新建一个gRPC服务,会内置一proto文件;内容如下,可以理解成是一个模板,通过这个模板 可以生成对应的类文件。.
syntax = "proto3"; //规范---标准---工具生成C#
option csharp_namespace = "Zhaoxi.gRPCDemo.DefaultServer";
package greet;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply);
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings.
message HelloReply {
string message = 1;
}
2,需要让这个文件生效,就必须要在项目文件中配置使用这个文件;GrpcServices=“Server”,这是服务端 的配置;
<ItemGroup>
<Protobuf Include="Protos\CustomMath.proto" GrpcServices="Server" />
<Protobuf Include="Protos\greet.proto" GrpcServices="Server" />
</ItemGroup>
3,编译,就可以通过这个模板生成一些类,包含这些类的方法;
客户端:
1,Vs新建一个控制台,作为客户端
2,把服务端的那个proto文件,连同文件一起Copy到客户端来。
3,配置客户端的项目文件,如下。请注意 GrpcServices=“Client”
<ItemGroup>
<Protobuf Include="Protos\greet.proto" GrpcServices="Client" />
<Protobuf Include="Protos\CustomMath.proto" GrpcServices="Client" />
</ItemGroup>
4,编译后,编写调用gRPC的方法如下:
private static async Task TestHello()
{
using (var channel = GrpcChannel.ForAddress("https://localhost:5001"))
{
var client = new Greeter.GreeterClient(channel);
var reply = await client.SayHelloAsync(new HelloRequest { Name = "朝夕教
育" });
Console.WriteLine("Greeter 服务返回数据: " + reply.Message);
}
}