04 使用gRPC实现客户端和服务端通信

使用gRPC实现客户端和服务端通信

参考文档:

基于C#的GRPC

1 创建项目和文件夹

GrpcClientDemo

GrpcServerDemo

Protos解决方案和文件夹

1.1 添加nuget依赖

客户端和服务器都要有依赖和gRPC_Objects文件夹

 <ItemGroup>
   <PackageReference Include="Google.Protobuf" Version="3.25.2" />
   <PackageReference Include="Grpc" Version="2.46.6" />
   <PackageReference Include="Grpc.Core" Version="2.46.6" />
   <PackageReference Include="Grpc.Tools" Version="2.46.6">
     <PrivateAssets>all</PrivateAssets>
     <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
   </PackageReference>
 </ItemGroup>

   <ItemGroup>
    <Protobuf Include="../Protos/*.proto" OutputDir="%(RelativePath)gRPC_Objects"></Protobuf>
   </ItemGroup>

 <ItemGroup>
   <Folder Include="gRPC_Objects\" />
 </ItemGroup>

1.2 添加hello.proto

syntax = "proto3";

message HelloRequest{
	string firstName=1;
	string lastName=2;
}

message HelloResponse{
	string message=1;
}

service HelloService{
	rpc Welcome(HelloRequest) returns (HelloResponse);
}

编译会自动生成代码

2 创建服务端代码

GServices/HelloServiceImpl.cs

using Grpc.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static HelloService;

namespace GrpcServerDemo.GServices
{
    public class HelloServiceImpl:HelloServiceBase
    {
        public override Task<HelloResponse> Welcome(HelloRequest request, ServerCallContext context)
        {
            var message = $"你好 {request.FirstName} {request.LastName}";
            return Task.FromResult(new HelloResponse { Message = message });                          
            //return base.Welcome(request, context);
        }
    }
}

Program.cs

using Grpc.Core;
using GrpcServerDemo.GServices;

namespace GrpcServerDemo
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            Server server = new Server()
            {
                Ports = {new ServerPort("localhost",7777,ServerCredentials.Insecure)},
                Services = {HelloService.BindService(new HelloServiceImpl())}               
            };

            try
            {
                server.Start();
                Console.WriteLine($"server is listening to port 7777");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"an error has been thrown: {ex}");
            }
            finally
            {
                if (server != null)
                {
                    await server.ShutdownAsync();
                }
            }
            
        }
    }
}

3 创建客户端代码

Program.cs


using Grpc.Core;

namespace GrpcClientDemo
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            Channel channel = new Channel("localhost:7777",ChannelCredentials.Insecure);

            try
            {
                await  channel.ConnectAsync();
                Console.WriteLine("the client connected successfully to the sever");

                var client=new HelloService.HelloServiceClient(channel);
                HelloResponse helloResponse = await client.WelcomeAsync(new HelloRequest
                {
                    FirstName="xie",
                    LastName="万能"
                });
                Console.WriteLine("接受到数据:"+helloResponse.Message);

                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"an error has been thrown: {ex}");
            }
            finally
            {
                if(channel != null)
                {
                    await channel.ShutdownAsync();
                }
            }
            
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值