TCP通信报错:无法读取传输连接数据,远程主机强制关闭连接
代码排查求助
错误提示
Unable to read data to the transport connection: An existing connection was forcibly closed by the remote host
问题描述
连接被远程服务器强制关闭,尝试多种修复手段均无效,但用Packet Sender调用时一切正常。调试确认错误出在stream.ReadAsync方法,其余代码逻辑无异常。
相关代码
// call TCP System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; byte[] ByteASCII_1 = Encoding.ASCII.GetBytes(AsciiPayload); TcpClient tcpClient = new TcpClient(); await tcpClient.ConnectAsync(ZgwIP, TCP_DIAG_PORT); NetworkStream stream = tcpClient.GetStream(); await stream.WriteAsync(ByteASCII_1, 0, ByteASCII_1.Length); byte[] buffer = new byte[1048]; int countByte = 0; string stringHex = string.Empty; while (stream.CanRead) { int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length); if (bytesRead <= 0) { break; } //string hexResponse = CryptoHelper.ByteArrayToHexString(buffer, bytesRead); //stringHex += hexResponse; //countByte += bytesRead; //if (countByte >= 74) //{ // break; //} } RTB_Logs.AppendText($"\n{stringHex}\n"); tcpClient.Close(); stream.Close();
已添加以下安全协议设置代码,但问题仍未解决:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
恳请帮忙排查代码中的问题。
内容的提问来源于stack exchange,提问作者Quang Ngô Văn
相关产品推荐
相关产品推荐

