0

I am trying to check the TCP connection to a localhost TCP server (ActiveMQ broker) 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 (ActiveMQ broker), 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?

4

2 回答 2

0

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.

于 2019-12-12T19:06:26.127 回答
0

这个

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

包装你的.Connect()电话。并且Task.Run()总是AggregateException在里面抛出真正的异常。为了解决这个问题,要么检查异常,要么更好地使用异步变体.Connect()

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

反而。

于 2019-12-12T17:08:00.273 回答