我试图用HttpWebRequest和HttpWebResponse连接到服务器,并且工作正常,但是我遇到另一个问题,我想知道服务器何时超时或断开连接,假设我的连接发生了问题,我想知道断开连接我如何在以下代码中理解这一点:

string uri = @"myUrl";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        request.Credentials = new NetworkCredential(User, Pass);
        ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
        byte[] buf = new byte[10000];
        int count = -1;
        String read = "";
        HttpWebResponse response;
        //MessageBox.Show("OK");
        //response = (HttpWebResponse)request.GetResponse();
        //count = response.GetResponseStream().Read(buf, 0, buf.Length);
        //read = Encoding.UTF8.GetString(buf, 0, count);
        //MessageBox.Show(read + "SALAM");
        //while (true)
        //{
        response = (HttpWebResponse)request.GetResponse();
        //while (true)
        //{
        do
        {
            count = response.GetResponseStream().Read(buf, 0, buf.Length);
            read += Encoding.UTF8.GetString(buf, 0, count);
        } while (response.GetResponseStream().CanRead && count != 0);

        if (read != "")
        {
            // MessageBox.Show(read);
            XDocument xdoc = XDocument.Parse(read);

            //Filter EventXML
            var lv1s = from lv1 in xdoc.Descendants("event")
                       select new
                       {
                           Event_id = lv1.Attribute("id").Value,
                           Header = lv1.Attribute("name").Value,
                           Children = lv1.Descendants("argument")
                       };
            List<event_details> event_detail = new List<event_details>();


            foreach (var lv1 in lv1s)
            {
                if (lv1.Event_id == event_id)
                    foreach (var lv2 in lv1.Children)
                    {
                        event_details x = new event_details();
                        x.type = lv2.Attribute("type").Value;
                        x.value = lv2.Attribute("value").Value;
                        event_detail.Add(x);
                    }
            }
            //inja chun ke daram rooye MsgDGV ke ye k Datagridview minevisam bayad hatman az Invoke estefade konam
            // ta kharabkari nashe:P:D
            Point detail_point = new Point();
            detail_point.X = MsgDGV.Width / 2 + (this.Width - MsgDGV.Width) / 2;
            detail_point.Y = MsgDGV.Height / 2 + (this.Height - MsgDGV.Height) / 2;
            Details detail = new Details(event_detail, timestamp, EVENT, detail_point);
            detail.ShowDialog();
            event_details.Abort();
        }

最佳答案

当Request.GetResponse()方法调用超时时,您需要捕获在调用WebException方法时抛出的HttpWebRequest.GetResponse。 GetResponse()方法可以抛出四个异常,因此您需要检查抛出的Exception的类型或捕获所需的特定异常类型,即:Catch(WebException ex){}。

请注意,您可以根据需要获取和设置WebRequest.Timeout属性。

// Set the 'Timeout' property in Milliseconds.
request.Timeout = 10000;


在您的代码中,您将HttpWebRequest.GetResponse()方法调用以及与GetResponse()调用公开的数据相关的所有代码包装在Try-Catch块中。
您还应该利用WebResponse实现IDisposable并使用using syntax来管理对象作用域和生存期这一事实,这样您就不必再引用不再需要的对象或作用域了。

try
{
    using (WebResponse response = request.GetResponse())
    {
            // ALL OTHER CODE
    }
}
catch (Exception ex)
{
    // Handle Exception
}

08-26 19:38