这是小弟写的一个代理服务器的方法.clientSock监听localhost的请求(其实就是用localhost作代理,有什么就传回什么,很简单没什么实际意义的代理),serverSock获取服务器的字节.然后这个DoRequest就是总的方法如果网页是一口气把byte都传送回来的话,网页显示没问题,但问题是,如果网页的Transfer-Encoding是chunked的话,这个方法就不行了.POST也貌似不能用...那位大大能够提供一个解析chunked的C#代码呢?最好是能够直接用在我最下面外边的else里面的(因为是草稿,所以会有些没什么意义的代码,抱歉了)        public void DoRequest()
        {
            System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
            //const int BUFSZ = 1024;            try
            {
                // IPAddress and IPEndPoint represent the endpoint that will
                //   receive the request.
                // Get the first IPAddress in the list using DNS.                IPAddress hostadd = Dns.GetHostEntry(Host).AddressList[0];
                if (Host == "localhost")
                {
                    hostadd = IPAddress.Loopback;
                }
                IPEndPoint remoteEndPoint = new IPEndPoint(hostadd, Port);                //Console.WriteLine(remoteEndPoint.ToString());                //Creates the Socket for sending data over TCP.
                Socket serverSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                serverSock.ReceiveTimeout = 20 * 1000; // Set time out (milliseconds)                // Connects to the host using IPEndPoint.
                serverSock.Connect(remoteEndPoint);
                serverSock.Send(RequestBytes, RequestBytes.Length, SocketFlags.None);                // Get the HTTP headers first
                List<byte> ResponseBytesList = new List<byte>();
                string header = "";
                while (true)
                {
                    byte[] bytes = new byte[1];
                    int bytesRec = serverSock.Receive(bytes, SocketFlags.None);
                    
                    header += System.Text.Encoding.UTF8.GetString(bytes, 0, bytesRec);
                    for (int i = 0; i < bytesRec; i++)
                    {
                        ResponseBytesList.Add(bytes[i]);
                    }                                        if (header.IndexOf("\r\n\r\n") > -1 || header.IndexOf("\n\n") > -1)
                    {
                        //Blank line found, header ends
                        break;
                    }
                }
                
                byte[] HeaderBytes = ResponseBytesList.ToArray();
                //Console.WriteLine(header.Equals(utf8.GetString(ResponseBytesList.ToArray())));                // Break up the headers
                string[] headers = header.Split(new char[] { '\n' });                string statusLine = headers[0];
                Console.WriteLine(header);
                bool isChunked = checkIfChunked(headers);                //List<byte> ContentBytesList = new List<byte>();                if (isChunked == false)
                {
                    //Console.WriteLine("Not chunked");
                    int contentLength = GetContentLength(headers);
                    clientSock.Send(HeaderBytes, HeaderBytes.Length, SocketFlags.None);
                    byte[] contentBytesArray = new byte[contentLength];
                    int index = 0;
                    while (index < contentLength)
                    {
                        byte[] bytes = new byte[1];
                        int bytesNowGot = serverSock.Receive(bytes, SocketFlags.None);
                        if (bytesNowGot != 0)
                        {
                            contentBytesArray[index] = bytes[0];
                            index++;
                        }
                    }                    
                    clientSock.Send(contentBytesArray, SocketFlags.None);                    
                }//If not chunked, it works
                else//If chunked, it doesnt'
                {
                    int chunkSize = 0;
                    string content = "";
                    clientSock.Send(HeaderBytes, HeaderBytes.Length, SocketFlags.None);
                    do
                    {
                        byte[] bytes = new byte[1];
                        serverSock.Receive(bytes);
                        content += utf8.GetString(bytes);
                        if (content.IndexOf("\r\n") > -1)
                        {
                            chunkSize = Int32.Parse(content.Substring(0, content.Length - 4), System.Globalization.NumberStyles.HexNumber);
                            Console.WriteLine("Chunk size: " + chunkSize);
                            bytes = new byte[chunkSize];
                            serverSock.Receive(bytes);
                            clientSock.Send(bytes);
                            content = "";
                        }                                        } while (chunkSize != 0);
                }
                
                serverSock.Shutdown(SocketShutdown.Both);
                serverSock.Close();
                clientSock.Shutdown(SocketShutdown.Both);
                clientSock.Close();
            }catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());                   
            }
        }// DoRequest

解决方案 »

  1.   

     public void DoRequest()
            {
                System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
                //const int BUFSZ = 1024;            try
                {
                    // IPAddress and IPEndPoint represent the endpoint that will
                    //   receive the request.
                    // Get the first IPAddress in the list using DNS.                IPAddress hostadd = Dns.GetHostEntry(Host).AddressList[0];
                    if (Host == "localhost")
                    {
                        hostadd = IPAddress.Loopback;
                    }
                    IPEndPoint remoteEndPoint = new IPEndPoint(hostadd, Port);                //Console.WriteLine(remoteEndPoint.ToString());                //Creates the Socket for sending data over TCP.
                    Socket serverSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    serverSock.ReceiveTimeout = 20 * 1000; // Set time out (milliseconds)                // Connects to the host using IPEndPoint.
                    serverSock.Connect(remoteEndPoint);
                    serverSock.Send(RequestBytes, RequestBytes.Length, SocketFlags.None);                // Get the HTTP headers first
                    List<byte> ResponseBytesList = new List<byte>();
                    string header = "";
                    while (true)
                    {
                        byte[] bytes = new byte[1];
                        int bytesRec = serverSock.Receive(bytes, SocketFlags.None);
                        
                        header += System.Text.Encoding.UTF8.GetString(bytes, 0, bytesRec);
                        for (int i = 0; i < bytesRec; i++)
                        {
                            ResponseBytesList.Add(bytes[i]);
                        }                                        if (header.IndexOf("\r\n\r\n") > -1 || header.IndexOf("\n\n") > -1)
                        {
                            //Blank line found, header ends
                            break;
                        }
                    }
                    
                    byte[] HeaderBytes = ResponseBytesList.ToArray();
                    //Console.WriteLine(header.Equals(utf8.GetString(ResponseBytesList.ToArray())));                // Break up the headers
                    string[] headers = header.Split(new char[] { '\n' });                string statusLine = headers[0];
                    Console.WriteLine(header);
                    bool isChunked = checkIfChunked(headers);                //List<byte> ContentBytesList = new List<byte>();                if (isChunked == false)
                    {
                        //Console.WriteLine("Not chunked");
                        int contentLength = GetContentLength(headers);
                        clientSock.Send(HeaderBytes, HeaderBytes.Length, SocketFlags.None);
                        byte[] contentBytesArray = new byte[contentLength];
                        int index = 0;
                        while (index < contentLength)
                        {
                            byte[] bytes = new byte[1];
                            int bytesNowGot = serverSock.Receive(bytes, SocketFlags.None);
                            if (bytesNowGot != 0)
                            {
                                contentBytesArray[index] = bytes[0];
                                index++;
                            }
                        }                    
                        clientSock.Send(contentBytesArray, SocketFlags.None);                    
                    }//If not chunked, it works
                    else//If chunked, it doesnt'
                    {
                        int chunkSize = 0;
                        string content = "";
                        clientSock.Send(HeaderBytes, HeaderBytes.Length, SocketFlags.None);
                        do
                        {
                            byte[] bytes = new byte[1];
                            serverSock.Receive(bytes);
                            content += utf8.GetString(bytes);
                            if (content.IndexOf("\r\n") > -1)
                            {
                                chunkSize = Int32.Parse(content.Substring(0, content.Length - 4), System.Globalization.NumberStyles.HexNumber);
                                Console.WriteLine("Chunk size: " + chunkSize);
                                bytes = new byte[chunkSize];
                                serverSock.Receive(bytes);
                                clientSock.Send(bytes);
                                content = "";
                            }                                        } while (chunkSize != 0);
                    }
                    
                    serverSock.Shutdown(SocketShutdown.Both);
                    serverSock.Close();
                    clientSock.Shutdown(SocketShutdown.Both);
                    clientSock.Close();
                }catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());                   
                }
            }// DoRequest