Despite having all the appropriate using
statements, calling Close
, having some exponential back off logic and recreating the TcpClient
I've still been seeing issues where the application cannot recover the TCP connection without an application restart. It keeps failing with a
System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host
.
But there is an option LingerState
on the TcpClient
that appears it may have solved the issue (might not know for a few months as my own hardware setup only fails about that often!). See MSDN.
// This discards any pending data and Winsock resets the connection.
LingerOption lingerOption = new LingerOption(true, 0);
using (var tcpClient = new TcpClient
{SendTimeout = 2000, ReceiveTimeout = 2000, LingerState = lingerOption })
...