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