端点不可用时 UdpClient 不会失败

UdpClient not failing when endpoint is unavailable

我的预期是,如果端点不可用,UdpClient.Connect() 方法会抛出一个我可以捕获的异常,例如,更改标签的文本以说明程序是否已连接到服务器与否。然而,尽管我已经关闭了我尝试连接的服务器,该方法还是顺利完成了。有什么方法可以解决这个问题,或者我应该尝试使用其他方法吗?

我当前的代码(IP 地址空白,但有效):

UdpClient chatConnection = new UdpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("xxx.xx.xxx.xxx"), 1000);

// Initialize client/server connection and set status text
try
{
    chatConnection.Connect(serverEndPoint);
    SL_Status.Text = "Connected";
}
catch (Exception ex)
{
    SL_Status.Text = "Not Connected";
    MessageBox.Show("Unable to connect to server. See console for logs.");
    Console.WriteLine(ex);
}

由于 UDP 是无连接的,因此检查客户端是否已连接不适用于它。 但是,有一种解决方法在某些情况下可能会起作用: answer by Yahia