I am setting timeout for a TcpClient using TcpClient.ReceiveTimeout property. When the TcpClient.Read() method throws an exception (“connected party did not properly respond after a period of time”) -naturally- after TcpClient.ReceiveTimeout miliseconds, TcpClient.Connected begins to return false.
Is that normal? Is there a way to prevent this? I want to get the exception but keep the connection open.
That is normal behavior.
You can set an infinite receive timeout to avoid this situation (infinite is the default. You can explicitly set it with 0 as the ReceiveTimeout property). However, that would cause problems in program responsiveness if there really is never a client on the other end. It may be better to log the connection failure and then create a new connection, depending on your exact use case.
Here’s the pattern I would typically use (pseudo-codeish. The connection method would normally be inline with exception handling):