C# Handling TcpClient and Networkstream Disconnects

By Dag, on December 30th, 2016

After a couple of day of kicking my ass, I've found a more or less universal way to handle
TCP disconnects with .NET/C#. I've tried timers and async (BeginRead/Write) ways without really hitting
the mark of what I wanted. I don't like to overcomplicate things either and those things needed callback
functions that I realized was abundant as I did not need the threading management it provides, so I ended
up with utilizing just try/catch with a loop flag and custom pinging and checking against the only two exceptions
that really matters. There's also no need for async as you can set the Read/WriteTimeout.

So, the timeouts won't block infinite waiting, allowing exception handling.
And exceptions will only trigger if data is reported available.
As well as a "ping", if a connection needs to be reportedly dead/alive with an arbitrary idle traffic period.