gRpc 官網(wǎng) 鏈接 新建服務端項目 在服務端內(nèi)先編寫一個 .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 無關(guān)的.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(); } } 新建控制臺客戶端項目 客戶端調(diào)用服務端 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; } } } } |
|