当前位置: 首页 > article >正文

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();
                }
            }
            
        }
    }
}

http://www.kler.cn/a/231936.html

相关文章:

  • 卷径计算(基于卷径变化微分方程计算实时卷径)
  • java小练习
  • 基于大语言模型意图识别和实体提取功能;具体ZK数值例子:加密货币交易验证;
  • day-83 最少翻转次数使二进制矩阵回文 II
  • 【一键整合包及教程】AI照片数字人工具EchoMimic技术解析
  • React Native 全栈开发实战班 - 网络与数据之网络请求基础
  • Go语言Gin框架安全加固:全面解析SQL注入、XSS与CSRF的解决方案
  • 倒计时61天
  • 实景三维数据库管理系统助力实景三维中国建设
  • 【C++修行之道】(引用、函数提高)
  • CMake编译JSONCPP库
  • JCIM | MD揭示PTP1B磷酸酶激活RtcB连接酶的机制
  • 视频上传 - 断点续传那点事
  • 相机图像质量研究(3)图像质量测试介绍
  • L1-088 静静的推荐
  • vue3+threejs+koa可视化项目——模型文件上传(第四步)
  • 2024年:用OKR管理你的生活
  • 简单说网络:TCP+UDP
  • 上海泗博HART转ModbusTCP网关HME-635应用案例之组态王和超声波液位计通信
  • 解决“org.apache.catalina.startup.Catalina.stopServer 未配置关闭端口。通过OS信号关闭服务器。服务器未关闭“
  • c++阶梯之类与对象(中)< 续集 >
  • Mac利用brew安装mysql并设置初始密码
  • <网络安全>《15 移动安全管理系统》
  • Pytorch+NCCL源码编译
  • 【Web】vulhub Fastjson反序列化漏洞复现学习笔记
  • Leetcode第383场周赛