.NET使用gRPC入门教程

参考:https://blog.csdn.net/liyazhen2011/article/details/84937455

 

1.新建工程GrpcClient、GrpcServer和GrpcLibrary

   添加 - 新建项目 - 控制台应用 GrpcClient、GrpcServer。

   添加 - 新建项目 - 类库 GrpcLibrary。 工程中的三个项目情况如下:

   

 

 

2.安装程序包Grpc

   三个项目GrpcClient、GrpcServer、GrpcLibrary均安装程序包Grpc。

   属性- 管理NuGet程序包 - 安装Grpc

 

 

3.安装程序包Google.Protobuf 

三个项目GrpcClient、GrpcServer、GrpcLibrary均安装程序包Google.Protobuf 。

属性- 管理NuGet程序包 - 安装Google.Protobuf 

 

 

4.安装程序包Grpc.Tools

 类库GrpcLibrary安装程序包Grpc.Tools。

 属性- 管理NuGet程序包 - 安装Grpc.Tools。

 

 

5.自定义服务

  在项目GrpcLibrary里添加HelloWorld.proto用以生成代码。

 

syntax = "proto3";
package GrpcLibrary;
service GrpcService {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}
 
message HelloRequest {
  string name = 1;
}
 
message HelloReply {
  string message = 1;
}

  

 

 把PACKAGES里的grpc_csharp_plugin.exe和protoc.exe拷到当前目录中

新建ProtocGenerate.cmd

protoc -I . --csharp_out . --grpc_out . --plugin=protoc-gen-grpc=grpc_csharp_plugin.exe HelloWorld.proto

并执行

 

 

服务端

using Grpc.Core;
using GrpcLibrary;
using System;
using System.Threading.Tasks;

namespace GrpcServer
{
    class GrpcImpl : GrpcService.GrpcServiceBase
    {
        // 实现SayHello方法
        public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
        {
            return Task.FromResult(new HelloReply { Message = "Hello " + request.Name });
        }
    }
    class Program
    {
        const int Port = 9007;

        public static void Main(string[] args)
        {
            Server server = new Server
            {
                Services = { GrpcService.BindService(new GrpcImpl()) },
                Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };
            server.Start();

            Console.WriteLine("GrpcService server listening on port " + Port);
            Console.WriteLine("任意键退出...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
    }
}

 

客户端:

using Grpc.Core;
using GrpcLibrary;
using System;

namespace GrpcClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Channel channel = new Channel("127.0.0.1:9007", ChannelCredentials.Insecure);

            var client = new GrpcService.GrpcServiceClient(channel);
            var reply = client.SayHello(new HelloRequest { Name = "April" });
            Console.WriteLine("来自" + reply.Message);

            channel.ShutdownAsync().Wait();
            Console.WriteLine("任意键退出...");
            Console.ReadKey();
        }
    }
}

 

posted @ 2019-10-15 10:28  mingwj  阅读(758)  评论(0)    收藏  举报