HttpWebRequest很慢

时间:2018-09-24 13:26:53

标签: c# tcp webrequest

我一直在运行C#TCP服务器,该服务器通过HTTP POST调用将数据传输到另一台服务器已经两年了。

从Windows Server 2008切换到2012后,请求将永久保留。在“接收”方面,它是如此之慢,以至于我用尽了线程并返回了508错误。我已经定时了通过HTTP请求的脚本。执行大约需要30-40毫秒。别担心。 如果我花了时间来制作HttpWebRequest,那大约是2秒,这一定是为什么我的Web服务器上的线程用完了。

这是我的请求代码:

public static string WRequest(string URL, string method, string postData)
{
    string responseData = "";
    try
    {
        ServicePointManager.Expect100Continue = false;
        ServicePointManager.UseNagleAlgorithm = false;
        ServicePointManager.CheckCertificateRevocationList = false;

        // System.Net.CookieContainer cookieJar = new System.Net.CookieContainer();
        System.Net.HttpWebRequest hwrequest =
          (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL);
       // hwrequest.CookieContainer = cookieJar;
        hwrequest.Accept = "*/*";
        hwrequest.AllowAutoRedirect = true;
        hwrequest.UserAgent = "http_requester/0.1";
        hwrequest.Timeout = 60000;
        hwrequest.Proxy = null;
        hwrequest.Method = method;
        if (hwrequest.Method == "POST")
        {
            hwrequest.ContentType = "application/x-www-form-urlencoded";
            // Use UTF8Encoding instead of ASCIIEncoding for XML requests:
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] postByteArray = encoding.GetBytes(postData);
            hwrequest.ContentLength = postByteArray.Length;
            System.IO.Stream postStream = hwrequest.GetRequestStream();
            postStream.Write(postByteArray, 0, postByteArray.Length);
            postStream.Close();
        }

        System.Net.HttpWebResponse hwresponse =
          (System.Net.HttpWebResponse)hwrequest.GetResponse();

        if (hwresponse.StatusCode == System.Net.HttpStatusCode.OK)
        {
            System.IO.Stream responseStream = hwresponse.GetResponseStream();
            System.IO.StreamReader myStreamReader =
              new System.IO.StreamReader(responseStream);
            responseData = myStreamReader.ReadToEnd();
            // MessageBox.Show(responseData);
        }
        hwresponse.Close();
    }
    catch (Exception e)
    {
        responseData = "An error occurred: " + e.Message;
        Console.WriteLine(e.ToString());
    }

    Console.WriteLine(responseData);

    return responseData;
}

我已经在Windows 10机器和服务器2012上进行了测试,但计时问题相同(2秒)。

关于可能出现问题的任何想法?我觉得我已经尝试了一切。

0 个答案:

没有答案