0

我在这个控制台程序中有一些问题。我想用这个循环向一个网站发送许多请求而没有响应,因为响应增加了更多延迟,我不需要响应。

所以在我运行这个程序之后,它只发送两个请求,然后它就停止了,什么也不做。请帮我解决这个问题。

namespace ConsoleApplication8
{
    class Program
    {
        static void Main(string[] args)
        {
            string post2;
            for (int i = 111; i < 222; i++)
            {
                post2 = i.ToString();
                System.Net.HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://google.com");
                request.Method = "POST";
                request.KeepAlive = true;
                request.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                request.ServicePoint.Expect100Continue = false;
                string postData = post2;
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                request.ContentLength = byteArray.Length;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);         
                Console.WriteLine(post2);
            }                              
        }
    }
}
4

1 回答 1

0

.NET 默认限制为两个连接。如果需要,您可以增加限制,但真正的问题是您没有关闭流。

namespace ConsoleApplication8
{
    class Program
    {
        static void Main(string[] args)
        {
            string post2;
            for (int i = 111; i < 222; i++)
            {
                post2 = i.ToString();
                System.Net.HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://google.com");
                request.Method = "POST";
                request.KeepAlive = true;
                request.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                request.ServicePoint.Expect100Continue = false;
                string postData = post2;
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                request.ContentLength = byteArray.Length;
                // You need to close the request stream when you're done writing to it.
                using(Stream dataStream = request.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);         
                    Console.WriteLine(post2);
                }
                // Even if you don't need the response, you still need to close it.
                request.GetResponse().Close();
            }                              
        }
    }
}
于 2013-04-16T14:13:34.107 回答