3

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

Don Rhummy
  • 24,730
  • 42
  • 175
  • 330

2 Answers2

0

Perhaps you could use the newer ConnectAsync method instead which even allows you to supply a CancellationToken in case you require your client-connecting task to abort prematurely.

using (var clientSocket = new TcpClient())
{
    //Connect async and wait for connection up to our timeout
    if (!clientSocket.ConnectAsync(hostIP, portNumber).Wait(TimeSpan.FromSeconds(5)))
    {
        throw new Exception("Connection timed out.");
    }
}
silkfire
  • 24,585
  • 15
  • 82
  • 105
  • Does this actually do something different or is it internally the same as BeginConnect? – Don Rhummy Dec 05 '16 at 20:44
  • The `ConnectAsync` is simply a more modern way of connecting to a socket client asynchronously, whereas `BeginConnect` seems to be more of a legacy method. See a more detailed answer here: http://stackoverflow.com/a/5765032/633098 – silkfire Dec 05 '16 at 20:56
0

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.

Don Rhummy
  • 24,730
  • 42
  • 175
  • 330