【发布时间】:2016-08-01 14:26:07
【问题描述】:
我想等待来自TcpClient 的客户端的缓慢响应,但无论我如何配置它都会在大约 20 秒后超时。这是我的尝试:
using (var client = new TcpClient { ReceiveTimeout = 9999999, SendTimeout = 9999999 })
{
await client.ConnectAsync(ip, port);
using (var stream = client.GetStream())
{
// Some quick read/writes happen here via the stream with stream.Write() and stream.Read(), successfully.
// Now the remote host is calculating something long and will reply if finished. This throws the below exception however instead of waiting for >20s.
var bytesRead = await stream.ReadAsync(new byte[8], 0, 8);
}
}
例外是IOException:
无法从传输连接中读取数据:连接 尝试失败,因为连接方没有正确响应 一段时间后,或建立连接失败,因为 连接的主机未能响应。
...其中包含SocketException:
连接尝试失败,因为连接方没有 一段时间后正确响应,或建立连接 失败,因为连接的主机没有响应
SocketErrorCode 是TimedOut。
20 多岁的seems to be an OS default on Windows 但不能通过与TcpClient 交互来从托管代码中覆盖它吗?否则我该如何等待回复?
我也尝试过老式的BeginRead-EndRead 方式,EndRead 也是如此。该问题也不是由 Windows 防火墙或 Defender 引起的。
【问题讨论】:
-
更新:如果我在 ReadAsync() 失败后再次尝试运行,我会得到“现有连接被远程主机强行关闭”。我怀疑远程主机会导致整个问题,但即使在此之前,我也找不到任何迹象表明它会关闭连接。
标签: c# .net sockets tcpclient networkstream