【问题标题】:TcpClient connection broken after timeout超时后 TcpClient 连接断开
【发布时间】:2012-12-04 20:02:34
【问题描述】:

我正在使用TcpClient.ReceiveTimeout 属性为 TcpClient 设置超时。当TcpClient.Read()方法抛出异常(“连接方在一段时间后没有正确响应”)时-自然-在TcpClient.ReceiveTimeout毫秒之后,TcpClient.Connected开始返回false。

这正常吗?有没有办法防止这种情况?我想获得异常但保持连接打开。

【问题讨论】:

    标签: c# .net sockets timeout tcpclient


    【解决方案1】:

    这是正常行为。

    您可以设置无限接收超时来避免这种情况(无限是默认值。您可以将其显式设置为 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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      • 2011-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      相关资源
      最近更新 更多