Non mi consiglia di provare a scrivere solo per testare la presa. E non inoltrare nemmeno sulla proprietà Connected di .NET.
Se vuoi sapere se il punto finale remoto è ancora attivo, è possibile utilizzare TcpConnectionInformation:
TcpClient client = new TcpClient(host, port);
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnections = ipProperties.GetActiveTcpConnections().Where(x => x.LocalEndPoint.Equals(client.Client.LocalEndPoint) && x.RemoteEndPoint.Equals(client.Client.RemoteEndPoint)).ToArray();
if (tcpConnections != null && tcpConnections.Length > 0)
{
TcpState stateOfConnection = tcpConnections.First().State;
if (stateOfConnection == TcpState.Established)
{
// Connection is OK
}
else
{
// No active tcp Connection to hostName:port
}
}
client.Close();
Vedere anche:
TcpConnectionInformation su MSDN
IPGlobalProperties su MSDN
descrizione TcpState stati
Netstat on Wikipedia
E qui è come un metodo di estensione su TcpClient.
public static TcpState GetState(this TcpClient tcpClient)
{
var foo = IPGlobalProperties.GetIPGlobalProperties()
.GetActiveTcpConnections()
.SingleOrDefault(x => x.LocalEndPoint.Equals(tcpClient.Client.LocalEndPoint));
return foo != null ? foo.State : TcpState.Unknown;
}
Sì. Lo strato di socket deve essere gestito utilizzando le eccezioni. L'eccezione IOException ha l'eccezione interna impostata su SocketException, che contiene tutte le informazioni richieste per rilevare timeout o socket chiusi in remoto. – Luca