<五>创建一个简单的GRPC客户端和服务端

前面已经使用了微软提供的grpc服务端和客户端,如何自己实现一个简单的?     官网文档直通车:grpc中文文档

看了下官方文档,那就按照官方文档,参考官网给的例子,一步一步来。

1、首先建立一个类库存放protos....

 

 

 2、引入Google.Protobuf、Grpc.Core、Grpc.Tools 三个包

 

 

 3、到本地nuget库下找到grpc.tools文件下面的两个解析插件,这两个插件用来生成grpc服务基类

 

 

 4、编写bat文件调用这两个插件根据proto文件生成客户端和服务端代码

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

5、双击此bat文件,自动生成代码

 

 

 6、新增一个服务控制台程序,新增一个实现类TestImpl

namespace AidenGRPC.Server
{
    public class TestImpl:AidenGRPC.RPCBase.TestServer.TestServerBase
    {
        public override Task<Feature> GetFeature(Point request, ServerCallContext context)
        {
            return Task.FromResult(new Feature { Name = "aiden", Location = request });
        }
    }
}

7、添加启动服务代码

   static void Main(string[] args)
        {
            const int Port = 30052;
            Grpc.Core.Server server = new Grpc.Core.Server
            {
                Services = { AidenGRPC.RPCBase.TestServer.BindService(new TestImpl()) },
                Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };
            server.Start();

            Console.WriteLine("server listening on port " + Port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();
            server.ShutdownAsync().Wait();
        }

 

 

 8、创建控制台客户端链接我们刚刚创建的服务并调用服务获取信息

 static void Main(string[] args)
        {     
            Channel channel = new Channel("127.0.0.1:30052", ChannelCredentials.Insecure);
            var client = new AidenGRPC.RPCBase.TestServer.TestServerClient(channel) ;
            Point p = new Point() { Latitude = 409146, Longitude = -88906 };
            Feature f= client.GetFeature(p);
            Console.WriteLine(string.Format("Name:{0},Latitude:{1},Longitude:{2}", f.Name, f.Location.Latitude, f.Location.Longitude));
            channel.ShutdownAsync().Wait();
            Console.WriteLine("Press any key to exit client...");
            Console.ReadKey();        
        }

9、先启动server 再启动client

 

 

 

这样一个简单的客户端和服务段就完成了。呵呵简单不。 

 

posted @ 2021-03-10 17:29  许轩霖  阅读(314)  评论(0)    收藏  举报