Search code examples
c#.netnetwork-programmingtcpclient

Why doesn't TcpClient.BeginConnect result's AsyncWaitHandle.WaitOne return false if the listening service is down?


I am making a connection to a service i created on another server via:

using (var clientSocket = new TcpClient())
{
    ...
    //Connect async
    var result = clientSocket.BeginConnect(hostIP, portNumber, null, null);

    //Wait for connection up to our timeout
    if (!result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5)))
    {
        //This is NEVER run
        throw new Exception("Connection timed out.");
    }

    //It makes it here but shouldn't!
}

If the other server is up but the service that listens on the port is down, this still returns true! (And if the server is down, it does properly throw the exception)

Why?

How do I make it fail if the service is down (and thus nothing's listening on that port)?


Solution

  • It would appear that there's no way to have it fail if there's nothing listening. Instead, you can use a ReadTimeout to handle the error of nothing listening on the other end.