以下内容对我有用,假设 ${PWD}/app 中的所有内容:
- 创建自签名证书|密钥:
openssl req \
-x509 \
-newkey rsa:2048 \
-keyout ./app/localhost.key \
-out ./app/localhost.crt \
-nodes \
-days 365 \
-subj "/CN=localhost"
- 运行时
我在容器中使用dotnet:
GRPC="50052"
docker run \
--rm --interactive --tty \
--volume=${PWD}/app:/app \
--workdir=/app \
--publish=${GRPC}:50051 \
mcr.microsoft.com/dotnet/sdk:5.0 \
bash
还有:
dotnet new console
# Optional
dotnet add package Google.Protobuf --version 3.8.0
dotnet add package Grpc --version 2.23.0
dotnet add package Grpc.Core --version 2.23.0
dotnet add package Grpc.Tools --version 2.23.0
- 代码
您的代码,但使用 repo 的 greet.proto 示例:
using Grpc.Core;
using System;
using System.Threading.Tasks;
using System.IO;
namespace app {
public class GreeterService: Greeter.GreeterBase {
public override Task<HelloReply> SayHello(
HelloRequest request,
ServerCallContext context
) {
Console.WriteLine("[SayHello] Entered");
return Task.FromResult(new HelloReply {
Message = "Hello " + request.Name
});
}
}
class Program {
const int Port = 50051;
static void Main(string[] args) {
var keyCertPair = new KeyCertificatePair(
File.ReadAllText(@"localhost.crt"),
File.ReadAllText(@"localhost.key")
);
var credentials = new SslServerCredentials(new []{
keyCertPair
});
var server = new Server {
Services = { Greeter.BindService(new GreeterService()) },
Ports = { new ServerPort("0.0.0.0", Port, credentials) }
};
server.Start();
Console.WriteLine("gRPC Server [:" + Port + "]");
Console.WriteLine("Press any key to stop the server...");
Console.ReadKey();
server.ShutdownAsync().Wait();
}
}
}
还有:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Google.Protobuf" Version="3.8.0" />
<PackageReference Include="Grpc" Version="2.23.0" />
<PackageReference Include="Grpc.Core" Version="2.23.0" />
<PackageReference Include="Grpc.Tools" Version="2.23.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup>
<Protobuf Include="greet.proto" />
</ItemGroup>
</Project>
- 添加
libc-dev
根据这个comment
您需要:
apt update && apt -y install libc-dev
- 测试:
GRPC="50052"
grpcurl \
-insecure \
-cert app/localhost.crt \
-key app/localhost.key \
-proto app/greet.proto \
-d '{"name":"Freddie"}' \
localhost:${GRPC} \
Greeter.SayHello
产量:
{
"message": "Hello Freddie"
}