string ans = "";
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.ContentType = "text/html";
            request.Method = "GET";
    HttpWebResponse res;
            Stream st;
            StreamReader sr=null;
            Encoding toword;
            try
            {
                 res = (HttpWebResponse)request.GetResponse();                 
            }
            catch (WebException ex)
            {
                res = (HttpWebResponse)ex.Response;                             
            }            if (res.ToString() == null)
                return ans;
            st = res.GetResponseStream();
            toword = null;
            if (!encode.ToUpper().Equals("UTF8"))
            {
                toword = Encoding.GetEncoding(encode);
            }
            else
            {
                toword = Encoding.UTF8;
            }            try
            {                
                sr = new StreamReader(st, toword);
                ans = sr.ReadToEnd();
                sr.Close();
                st.Close();
            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.ToString());
                sr.Close();
                st.Close();
            }
            return ans;
    用C#写的多线程爬虫,主要是用了HttpWebRequest和HttpWebResponse做的,在运行过程中,设定5个爬虫,爬取某网站上10000个网页,开始没有问题,但是运行一段时间后报这样的异常:System.IO.IOException 无法从传输连接中读取数据: 远程主机强迫关闭了一个现有的连接  ---> System.Net.Sockets.SocketException: 远程主机强迫关闭了一个现有的连接。
   在 System.Net.Sockets.NetworkStream.Read--- 内部异常堆栈跟踪的结尾 ---
   在 System.IO.StreamReader.ReadToEnd()
    有的时候可以成功爬取6000多个网页,有时候几百个就报这个异常,在网上看了很多解决方案都不行啊,我看的方法有:1,把getResponse方法放到Trycatch块里面去; 2.把防火墙关掉 但是都不行,我怀疑是长时间爬取一个网站,被它服务器的安全措施给拒绝连接了。
C#  多线程 服务器 连接

解决方案 »

  1.   

    是的,,,,服务器如果做了处理,当同一IP访问次数过多,就会被认为是 采集器来了,就会做出相应,,,,,www.aaspx.com 个人观点,,
      

  2.   

    网络报错不属于程序逻辑异常,应该用try给屏蔽掉异常信息。轻而易举就崩溃,怎么当爬虫?
      

  3.   

       if (res.ToString() == null)
                    return ans;这个代码严重错误。
      

  4.   

    但是我已经把出错的ReadToEnd这条代码放到Try...Catch里面去了啊