简体   繁体   English

我的IsConnected始终返回true

[英]My IsConnected always returns true

Test-cases: 测试用例:

  1. Before connection starts it should return false 在连接开始之前,它应该返回false
  2. Connection is closed by other end return false 连接被其他结束返回false关闭
  3. Connection is closed by the client return false 连接由客户端返回false关闭
  4. Connection exists even if no data is avaliable return true 即使没有数据可用,也存在连接返回true

     class MyConnection { //Assume I have all initialization for _socket public bool IsConnected() { return !(_socket.Poll(1, SelectMode.SelectRead) && _socket.Available == 0); } private Socket _socket; 

    } }

     class Test { static void Main(string[] args) { MyConnection my = new MyConnection() if(my.IsConnected()) /*always return true even when I am not connected*/; } } 

Any ideas how to prevent that? 任何想法如何预防?


So far, none of the answers were satisfactory.... 到目前为止,没有一个答案令人满意......

The following can be done: 可以完成以下操作:

   public bool IsConnected()
        {

            bool bConnected = false;
            bool bState = _socket.Poll(1, SelectMode.SelectRead);
            try
            {
                if (bState && (_socket.Available == 0))
                    bConnected = false;
                else
                    bConnected = true;
            }
            catch (SocketException)
            {
                //_socket.Available can throw an exception
                bConnected = false;
            }

            return bConnected;
        }

I think your _socket.Poll() call is backwards. 我认为你的_socket.Poll()调用是倒退的。 If the poll fails, that will help the method evaluate as true rather than false. 如果轮询失败,那将有助于该方法评估为true而不是false。 Try this: 尝试这个:

public bool IsConnected()
{
    return !(!_socket.Poll(1, SelectMode.SelectRead)
                                && _socket.Available == 0);

}

I'm also not sure it's a good idea to make _socket.Available part of this check. 我也不确定将_socket.Available作为此检查的一部分是个好主意。 According to the documentation , a return value of 0 just means that "no data is queued in the network buffer." 根据文档 ,返回值0只表示“没有数据在网络缓冲区中排队”。 That could very easily be true even of a connected socket. 即使是连接的插座,这也很容易实现。

I'm not sure exactly what you're trying to achieve, but assuming you're trying to tell if the connection has been broken, this post may be helpful: 我不确定你想要实现的目标,但假设你试图判断连接是否已被破坏,这篇文章可能会有所帮助:

How can I tell if the connection has been broken in my sockets based client? 如何判断基于套接字的客户端连接是否已断开?

Edit: A troubleshooting step would be to determine which of the two boolean expressions are returning false, or if they are both returning false. 编辑:故障排除步骤是确定两个布尔表达式中的哪一个返回false,或者它们是否都返回false。

It looks to me like you may not get the functionality you are expecting from the Socket class. 在我看来,你可能无法获得你期望从Socket类中获得的功能。 My understanding is that the Socket class is only aware of the connection state as of the last socket operation. 我的理解是Socket类只知道最后一个套接字操作的连接状态。

Note that the Poll method has some limitations: 请注意, Poll方法有一些限制:

This method cannot detect certain kinds of connection problems, such as a broken network cable, or that the remote host was shut down ungracefully. 此方法无法检测某些类型的连接问题,例如网络电缆损坏,或者远程主机无法正常关闭。 You must attempt to send or receive data to detect these kinds of errors. 您必须尝试发送或接收数据以检测这些类型的错误。

This would imply that in the event of an ungraceful disconnect, it would be normal for a socket to continue to report true until a subsequent socket operation times out (which may explain the several minute delay you experienced in your previous post on this). 这意味着如果出现非正常的断开连接,套接字继续报告为真,直到后续套接字操作超时(这可以解释您在之前的帖子中经历的几分钟延迟)是正常的。

This means that if you want to detect ungraceful disconnects, you will likely need to implement an application level heartbeat/ping, as suggested in a previous answer . 这意味着如果要检测不合适的断开连接,您可能需要实现应用程序级心跳/ ping,如上一个答案中所述 You may need to play with the interval between the pings, otherwise you lose a degree of fault tolerance and a lag spike may cause unwanted reports of a disconnect. 您可能需要使用ping之间的间隔,否则您将失去一定程度的容错能力,并且延迟峰值可能会导致不需要的断开连接报告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM