gRpc 官网 链接
新建服务端项目
在服务端内先编写一个 .proto 文件
greet.proto
syntax = "proto3"; service Greeter { rpc SayHello (HelloRequest) returns (HelloReply); } message HelloRequest { string name = 1; } message HelloReply { string message = 1; }
服务端生成 .proto 代码为 C# NutGet Install-Package Grpc.Tools
找到tools 从里面选择自己电脑的版本
把 protoc.exe 、 grpc_csharp_plugin.exe 复制出来和 .proto 文件放在一起
编写一个 .cmd 文件和 .proto 文件放在一起,插入生成代码的指令。(注意 greet.proto 这是 .proto 文件名)
protoc -I . --csharp_out . --grpc_out . --plugin=protoc-gen-grpc=grpc_csharp_plugin.exe greet.proto
点击cmd 生成 会获得两个C#文件。
新建类GreeterService
并在使用客户端之前启动(启动服务端之前,要先排除与.Net 无关的.proto文件,不然直接运行会报错的)
public class GreeterService : Greeter.GreeterBase { private readonly ILogger<GreeterService> _logger; public GreeterService(ILogger<GreeterService> logger) { _logger = logger; } public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context) { _logger.LogInformation("Saying hello to {Name}", request.Name); return Task.FromResult(new HelloReply { Message = "Hello " + request.Name }); } } class Program { const int Port = 2020; static void Main(string[] args) { Server server = new Server { Services = { Greeter.BindService(new GreeterService()) }, Ports = { new ServerPort("127.0.0.1", 2020, ServerCredentials.Insecure) } }; server.Start(); Console.WriteLine("127.0.0.1"); Console.WriteLine("GrpcService server listening on port " + Port); Console.WriteLine("任意键退出..."); Console.ReadKey(); } }
新建控制台客户端项目
客户端调用服务端
namespace gRPCClient { class Program { static void Main(string[] args) { // The port number(5001) must match the port of the gRPC server. Channel channel = new Channel("127.0.0.1", 2020, ChannelCredentials.Insecure); var client = new Greeter.GreeterClient(channel).WithHost("127.0.0.1"); try { var reply = client.SayHelloAsync(new HelloRequest { Name = "Zhang San" }); Console.WriteLine("来自" + reply.ResponseAsync.Result); channel.ShutdownAsync().Wait(); Console.WriteLine("Greeting: " + reply.ResponseAsync.Result); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } catch (Exception ex) { throw ex; } } } }