Test-cases:
- Before connection starts it should return false
- Connection is closed by other end return false
- Connection is closed by the client return false
Connection exists even if no data is avaliable return 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;
}