当前位置:编程学习 > C#/ASP.NET >>

socket 请求服务器页面怎么返回空???

public string GetClientBySocket(string UrlString)
        {
            //string HostName = Dns.GetHostEntry(UrlString).ToString();
            IPAddress[] ips = Dns.GetHostAddresses(UrlString);

            IPAddress ip = ips[0];

            IPEndPoint serverhost = new IPEndPoint(ip, 80);
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(serverhost);

            string httpReq = "GET " + UrlString + " HTTP/1.0 \r\n";
            httpReq += "Host:" + UrlString + " \r\n";
            httpReq += "User-Agent: Mozilla/4.0 (compatible; MSIE 5.00; Windows xp) \r\n";
            httpReq += "Accept:*/* \r\n";
            httpReq += "Connection:Keep-Alive \r\n\r\n";
            string txtHTML = "";
            try
            {
                clientSocket.Send(System.Text.Encoding.ASCII.GetBytes(httpReq) );

                Byte[] buffer = new byte[10240];

                int byteCount = clientSocket.Receive(buffer, buffer.Length, 0);

                txtHTML = Encoding.ASCII.GetString(buffer, 0, byteCount);

                while (byteCount > 0)
                {
                    byteCount = clientSocket.Receive(buffer, buffer.Length, 0);
                    //txtHTML = txtHTML + Encoding.Default.GetString(buffer, 0, byteCount);
                    txtHTML = txtHTML + Encoding.GetEncoding("gb2312").GetString(buffer, 0, byteCount);
                }

                clientSocket.Close();
                int index = txtHTML.IndexOf("Location:");
                if (index > 0)
                {
                    MatchCollection MatchList = Regex.Matches(txtHTML, "Location:(?<URL>.*?)\r");
                    string url = MatchList[0].Groups["URL"].Value;
                    txtHTML = GetClientBySocket(url);
                }
            }
            catch (Exception err)
            {
                // string errMessage = String.Format("网络错误,Socket网络数据下载失败:{0}", HostName);
                // string Forder = ConfigurationManager.AppSettings["LogFolder"];
                // ILogWriter LogWriter = new WinLogWriter();
                // LogWriter.AddLog(err, errMessage, Forder);
                txtHTML = "wrong" + err.Message.ToString();
            }
           return txtHTML;
        }
补充:.NET技术 ,  ASP.NET
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,