Detect if the other end of a TcpClient has disconnected

Given a TcpClient instance, I really needed to know ASAP if the other end of the connection had disappeared / disconnected unexpectedly, or something else that causes the communication to be broken.

public bool GetIsAlive()
{
	if (TcpClient.Client is null) return false;
	if (IsDisposed) return false;
	try
	{
		TcpClient.Client.Blocking = false;
		bool hasDisconnected = TcpClient.Client.Poll(0, SelectMode.SelectRead) && TcpClient.Client.Available == 0;
		return !hasDisconnected;
	}
	catch (SocketException)
	{
		return false;
	}
}

This seems to do the trick very nicely.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *