为什么TcpClient.Connect()抛出System.AggregateException

我正在尝试使用以下代码检查与本地TCP服务器(activeMQ代理)的TCP连接:

SELECT
  p.id,p.post_title,p.post_content,p.post_excerpt,t.name AS product_category,t.term_id AS product_id,tt.term_taxonomy_id AS tt_term_taxonomia,tr.term_taxonomy_id AS tr_term_taxonomia,pm1.meta_value AS price
FROM wp_posts p 
LEFT JOIN wp_postmeta pm1 ON pm1.post_id = p.ID AND pm1.meta_key = '_price'
JOIN wp_term_relationships AS tr ON tr.object_id = p.ID
JOIN wp_term_taxonomy AS tt ON tt.taxonomy = 'product_cat'
                           AND tt.term_taxonomy_id = tr.term_taxonomy_id 
JOIN wp_terms AS t ON t.term_id = tt.term_id
WHERE p.post_type in('product','product_variation') AND p.post_status = 'publish'
ORDER BY
  CASE WHEN p.post_parent = 0 THEN id else post_parent END,CASE WHEN p.post_parent = 0 THEN 1 else 2 END;

我停止了本地主机服务器(activeMQ代理),并尝试运行上述代码。它抛出了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"); } 。当我启动服务器并运行代码时;它连接到服务器。

根据documentation of TcpClient.Connect,它表示将抛出以下其中一项:

  • System.aggregateexception
  • ArgumentNullException
  • ArgumentOutOfRangeException
  • SocketException
  • ObjectDisposedException
  • SecurityException

为什么会抛出NotSupportedException

qqq279985481 回答:为什么TcpClient.Connect()抛出System.AggregateException

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

结束您的.Connect()通话。并且Task.Run()总是抛出AggregateException并带有真正的异常。为了解决此问题,请检查异常,甚至更好地使用.Connect()的异步变体:

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

相反。

,

我最后要做的是:

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.");
            }

它似乎正在工作。

本文链接:https://www.f2er.com/2932418.html

大家都在问