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