我正在尝试将我的代码从 Grpc.Core 更新到 Grpc.Net,并且我从客户端/服务器连接部分开始。
在服务器端,我像这样配置 Kestrel:
private void CreateServer()
{
_server = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseKestrel();
webBuilder.ConfigureKestrel(options =>
{
options.Listen(IPAddress.Any, _port, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http2;
listenOptions.UseHttps();
});
});
webBuilder.ConfigureServices(services =>
{
services.AddCodeFirstGrpc(options =>
{
options.MaxReceiveMessageSize = int.MaxValue;
options.MaxSendMessageSize = int.MaxValue;
});
});
webBuilder.Configure((IApplicationBuilder app) =>
{
app.UseRouting();
app.UseEndpoints(endpoints => endpoints.MapGrpcService<GrpcService>());
});
}).Build();
_server.RunAsync();
}
在客户端,我尝试像这样连接:
private IGrpcService CreateClient()
{
var channelOption = new GrpcChannelOptions
{
MaxReceiveMessageSize = int.MaxValue,
MaxSendMessageSize = int.MaxValue,
};
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
var address = $"https://{_host}:{_port}";
Channel = GrpcChannel.ForAddress(address, channelOption);
IGrpcService client = Channel.CreateGrpcService<IGrpcService>();
client.SayHello("TESTING123");
return client;
}
我会收到以下错误:
Grpc.Core.RpcException: Status(StatusCode="Internal", Detail="Error starting gRPC call. HttpRequestException: No connection could be made because the target machine actively refused it. (testmachine1:59) SocketException: No connection could be made because the target machine actively refused it.", DebugException="System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it. (testmachine1:59)
需要注意的一些事情是端口肯定是相同的。我记录了它们以确认我在地址中使用主机名。但是,我尝试使用
Dns.GetHostAddresses(_host)
获取 IP 地址,但发生了相同的错误。另请注意,客户端和服务器是两台不同的机器,我检查了主机的日志,它确实启动了,并且我看到它正在侦听指定的端口。此设置也适用于 Grpc.Core 代码优先配置
有什么想法可能会发生这种情况吗?任何帮助将不胜感激,因为我不确定我做错了什么。
没关系,我在
app.UseDeveloperExceptionPage()
中添加了 Configure
,它给了我更多的日志可供使用。事实证明,我需要在 services.AddScoped(_ => new GrpcService());
中添加 ConfigureServices
才能使其正常工作。虽然现在它只适用于 http,所以我需要删除 UseHttps()
行