c#使用grpc

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/slwsss/article/details/69733224
        static readonly Marshaller<string> _marshaller = new Marshaller<string>(p => Encoding.UTF8.GetBytes(p), p => Encoding.UTF8.GetString(p));

            ///服务端
            var server = new Server();
            server.Ports.Add(new ServerPort("127.0.0.1", 12345, ServerCredentials.Insecure));
            var s = ServerServiceDefinition.CreateBuilder();
            s.AddMethod(new Method<string, string>(MethodType.Unary, "service", "say", _marshaller, _marshaller),
                new UnaryServerMethod<string, string>((request, context) => Task.FromResult(request + "_" + DateTime.Now.ToString())));
            server.Services.Add(s.Build());
            server.Start();
            Console.ReadLine();
            server.ShutdownAsync().Wait();
     
            ///客户端
            Channel channel = new Channel("127.0.0.1", 12345, ChannelCredentials.Insecure);
            var client = new Client(channel);
            Console.WriteLine(client.say("==========="));
            channel.ShutdownAsync().Wait();
        
        public class Client : ClientBase
        {
            public Client(Channel channel) : base(channel)
            {
                this.Channel = channel;
            }
            public Channel Channel;

            public string say(string str)
            {
                return this.CallInvoker.BlockingUnaryCall<string, string>(_Method, null, new CallOptions(), str);
            }

            static readonly Method<string, string> _Method = new Method<string, string>(MethodType.Unary, "service", "say", _marshaller, _marshaller);
        }

猜你喜欢

转载自blog.csdn.net/slwsss/article/details/69733224