满纸荒唐言,一把心酸泪,都云作者痴,谁解其中味。 技术博客 心情随笔
gRPC基础:C#服务端与客户端代码示例
2025/4/9 170

导航

1前言

2编写proto文件

3C#服务端

4C#客户端

1 前言

之前的两篇文章基于C++演示了gRPC的服务端、客户端以及Protobuf应用与代码示例,本文将基于C#演示gRPC的服务端与客户端。

gRPC基础:C++服务端与客户端代码示例

gRPC进阶:通过stream实现观察者模式来源:https://www.wubayue.com

2 编写proto文件

编写School.proto文件

// 指定版本
syntax = "proto3";
// 命名空间
package GrpcDemo;

// 性别
enum Sex {
    Unknow = 0;
    Male = 1;
    Female = 2;
} 

// 学生
message Student {
    int32 StudentID = 1;
    string Name = 2;
    Sex Sex = 3;
}

// 获取所有学生信息请求
message GetStudents_Request{
}

// 获取所有学生信息响应
message GetStudents_Response {
    repeated Student Students = 1;
}

service School {
    // 获取所有学生信息
    rpc GetStudents(GetStudents_Request) returns (GetStudents_Response) {}
} 

生成gRPC框架代码

在NuGet中安装包Grpc.Tools。

安装成功后,将安装目录中的protoc.exe与grpc_csharp_plugin.exe拷贝至.proto文件所在目录。

执行命令生成gRPC框架代码(School.cs、SchoolGrpc.cs):

protoc --proto_path=./ --csharp_out=./gen_csharp --grpc_out=./gen_csharp --plugin=protoc-gen-grpc=./grpc_csharp_plugin.exe School.proto

如果生成失败可能需要安装最新的 C++运行时来源:https://www.wubayue.com

3 C#服务端

在NuGet中安装包Google.Protobuf、Grpc.Core。

将之前步骤中生成的School.cs、SchoolGrpc.cs拷贝至项目中。

编写SchoolService.cs向框架中填充业务逻辑:

using Grpc.Core;

namespace GrpcDemo.Server
{
    // 在框架中填充业务逻辑
    public class SchoolService : GrpcDemo.School.SchoolBase
    {
        public override Task<GetStudents_Response> GetStudents(GetStudents_Request request, ServerCallContext context)
        {
            Console.WriteLine("Received request.");
            var response = new GetStudents_Response();
            response.Students.AddRange(new List<Student> { 
                new Student { StudentID = 1, Name = "张三", Sex = Sex.Male },
                new Student { StudentID = 2, Name = "李四", Sex = Sex.Male },
                new Student { StudentID = 3, Name = "王五", Sex = Sex.Unknow }
            });
            return Task.FromResult(response);
        }
    }
} 

监听端口启动gRPC服务端:来源:https://www.wubayue.com

using Grpc.Core;

namespace GrpcDemo.Server
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine($"Grpc server start {new GrpcServer().Start().ToString()}");
            Console.ReadLine();
        }
    }

    public class GrpcServer
    {
        private bool _isStarted = false;

        // 在线程中启动gRPC服务
        public bool Start()
        {
            if (_isStarted)
                return false;

            Thread t = new Thread(() =>
            {
                Grpc.Core.Server server = new Grpc.Core.Server
                {
                    Services = { GrpcDemo.School.BindService(new SchoolService()) },
                    Ports = { new ServerPort("0.0.0.0", 8888, ServerCredentials.Insecure) }
                };
                server.Start();
            });
            t.IsBackground = true;
            t.Start();

            _isStarted = true;
            return true;
        }
    }
} 

4 C#客户端

在NuGet中安装包Google.Protobuf、Grpc.Core、Grpc.Net.Client。

将之前步骤中生成的School.cs、SchoolGrpc.cs拷贝至项目中。

编写客户端代码:来源:https://www.wubayue.com

using Grpc.Core;

namespace GrpcDemo.Client
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 网络连接通道
            Channel channel = new Channel("127.0.0.1:8888", ChannelCredentials.Insecure);
            // 客户端
            var client = new GrpcDemo.School.SchoolClient(channel);
            // 调用
            var response = client.GetStudents(new GetStudents_Request { });

            foreach (Student student in response.Students)
            {
                Console.WriteLine($"{student.StudentID}, {student.Name}, {student.Sex}");
            }
        }
    }
} 

<全文完>