Why is TcpClient.Connect() throwing System.AggregateException

231 Views Asked by At

I am trying to check the TCP connection to a localhost TCP server using following code:

string host = "localhost";
int port = 61616;
using (TcpClient tcpClient = new TcpClient())
{
    try
    {


        Task t = Task.Run(() => {
            tcpClient.Connect(host, port);
        });
        Console.WriteLine("Connected.");
        TimeSpan ts = TimeSpan.FromMilliseconds(150);
        if (!t.Wait(ts))
        {
            Console.WriteLine("The timeout interval elapsed.");
            Console.WriteLine("Could not connect to: {0}", port);// ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Port.ToString());
        }
        else
        {
            Console.WriteLine("Port {0} open.", port);
        }
     }
    catch (UnauthorizedAccessException )
    {
        Console.WriteLine("Caught unauthorized access exception-await behavior");
    }
    catch (AggregateException )
    {
        Console.WriteLine("Caught aggregate exception-Task.Wait behavior");
    }

I stopped the localhost server, and tried to run the above code. It threw System.AggregateException. When I started the server and ran the code; it connects to the server.

According to the documentation of TcpClient.Connect it says it will throw one of the following:

  • ArgumentNullException
  • ArgumentOutOfRangeException
  • SocketException
  • ObjectDisposedException
  • SecurityException
  • NotSupportedException

Why will it throw System.AggregateException?

2

There are 2 best solutions below

1
On

What i did finally is:

tcpClient.ReceiveTimeout = 5000;
 tcpClient.SendTimeout = 5000;
 tcpClient.Connect(host, port);
 catch (SocketException) {
                Console.WriteLine("Could not connect to: {0}", port);
                Console.WriteLine("Socket exception. Check host address and port.");
            }

It seems to be working.

0
On

This

Task t = Task.Run(() => {
    tcpClient.Connect(host, port);
});

wraps your .Connect() call. And Task.Run() always throws AggregateException with the real exception inside it. In order to fix this either inspect the exception or even better use the asynchronous variant of .Connect():

Task t = tcpClient.ConnectAsync(host, port);

instead.