2
我的期望是,如果端點不可用,UdpClient.Connect()
方法會拋出一個異常,我可以捕獲並更改標籤的文本以說明程序是否連接到服務器與否。但是,儘管我關閉了要連接的服務器,但該方法完成後沒有任何問題。有什麼辦法來解決這個問題,或者我應該嘗試的其他方法?當端點不可用時,UdpClient不會失敗
我當前的代碼(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的連接規則更爲寬鬆,不知道它試圖使用'Connect()'方法幾乎沒用 – dantdj