【问题标题】:UdpClient not failing when endpoint is unavailable端点不可用时 UdpClient 不会失败
【发布时间】:2017-01-23 00:07:57
【问题描述】:

我的期望是,如果端点不可用,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);
}

【问题讨论】:

    标签: c# udpclient


    【解决方案1】:

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

    【讨论】:

    • 啊,完美,谢谢!我知道 UDP 的连接规则比较宽松,不知道尝试使用 Connect() 方法几乎没用哈哈
    猜你喜欢
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 2018-07-24
    相关资源
    最近更新 更多