grpc RpcException 发送时发生

grpc RpcException Occured when I send

我只想连接并将字符串发送到 Grpc 服务器并获取字符串。

服务端是python写的,客户端是C#写的

它在 python 客户端中有效

这是我的客户端代码和异常日志。

客户代码

static async Task Main(string[] args)
{
    using var channel = GrpcChannel.ForAddress("http://1.2.3.4:5555");
    var client = new GRPCSerivce.GRPCSerivceClient(channel);
    var reply = await client.SynAck_ResultStringAsync(new DataRequest { Keys = "12345" });
    Console.WriteLine($"Return: {reply.Datas}");
    Console.WriteLine("Press any key to exit");
    Console.ReadLine();
}

错误发生在这一行

var reply = await client.SynAck_ResultStringAsync(new DataRequest { Keys = "12345" });

这是异常代码

Grpc.Core.RpcException: 'Status(StatusCode="Unavailable", Detail="Error starting gRPC call. HttpRequestException: An error occurred while sending the request. IOException: The response ended prematurely.", DebugException="System.Net.Http.HttpRequestException: An error occurred while sending the request.
 ---> System.IO.IOException: The response ended prematurely.
   at System.Net.Http.HttpConnection.FillAsync()
   at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed)
   at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at Grpc.Net.Client.Internal.GrpcCall`2.RunCall(HttpRequestMessage request, Nullable`1 timeout)")'

服务器已经明确声明了端口号。

为什么会出现这种异常?

据我所知你需要设置

AppContext.SetSwitch(
    "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

如果您想使用不安全的连接。尝试使用 https 或设置开关。请看here.

如果您不需要使用 TLS 连接,请尝试通过执行以下操作来构建通道:

using var channel = new Channel("1.2.3.4", 5555, ChannelCredentials.Insecure);

如果仍然无效,您可以向我们提供有关您的服务器和客户端的更多信息(实施、环境等)。之后我可以更新我的答案。