我正在使用TcpClient.ReceiveTimeout
属性为 TcpClient 设置超时。当TcpClient.Read()
方法抛出异常(“连接方在一段时间后没有正确响应”)时 - 自然 -TcpClient.ReceiveTimeout
毫秒后,TcpClient.Connected
开始返回 false。
这正常吗?有没有办法防止这种情况?我想获得异常但保持连接打开。
那是正常的行为。
您可以设置无限接收超时来避免这种情况(无限是默认值。您可以将其显式设置为 0 作为 ReceiveTimeout 属性)。但是,如果另一端真的没有客户端,这将导致程序响应能力出现问题。根据您的具体用例,记录连接失败然后创建新连接可能会更好。
这是我通常会使用的模式(伪代码。连接方法通常与异常处理内联):
while (!done)
{
// Try to connect with a reasonable ReceiveTimeout
connected = EstablishTheConnectionAndHandleAnyException();
if (connected)
{
// Do useful work
done = true;
}
else
{
// Receive timeout
// If interactive, give the user an opportunity to abort
// by setting done = true
// At least log the situation
}
}