user192936
user192936

Reputation:

TcpClient connection broken after timeout

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.

Upvotes: 0

Views: 1094

Answers (1)

Eric J.
Eric J.

Reputation: 150228

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):

while (!done)
{
    // Try to connect with a reasonable ReceiveTimeout
    connected = EstablishTheConnectionAndHandleAnyException();
    if (connected)
    {
        // Do useful work
        done = true;
    }
    else
    {
        // Receive timeout
        // If interactive, give the user an opportunity to abort
        //    by setting done = true
        // At least log the situation
    }
}

Upvotes: 1

Related Questions