日期:2014-05-17 浏览次数:20780 次
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Net; using System.Threading; namespace LocalhostProxy { class Program { static void Main(string[] args) { const int DEFPORTNUM = 8081; int port2use = DEFPORTNUM; const int BACKLOG = 10; // maximum length of pending connections queue Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Establish the local endpoint for the socket IPAddress ipAddress = IPAddress.Loopback; IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port2use); listener.Bind(localEndPoint); listener.Listen(BACKLOG); System.Console.WriteLine("Listening ... " + localEndPoint.ToString()); while (true) { Socket sock = listener.Accept(); //if(sock.Connected) // System.Console.WriteLine("Connection established"); RequestHandler rh = new RequestHandler(sock); Thread rhThread = new Thread(new ThreadStart(rh.DoRequest)); rhThread.Start(); } } } class RequestHandler { public RequestHandler(Socket sock) { System.Text.Encoding utf8 = System.Text.Encoding.UTF8; List<byte> requestBytesList = new List<byte>(); // Get the HTTP headers first Header = ""; while (true) { RequestBytes = new byte[1]; int bytesRec = sock.Receive(RequestBytes); requestBytesList.Add(RequestBytes[0]); Header += System.Text.Encoding.ASCII.GetString(RequestBytes, 0, bytesRec); if (Header.IndexOf("\r\n\r\n") > -1 || Header.IndexOf("\n\n") > -1) { break; } } System.Console.WriteLine("*** Headers ***\n " + Header); // Break up the headers string[] headers = Header.Split(new char[] { '\n' }); string requestLine = headers[0]; string[] requestLineElements = requestLine.Split(new char[] { ' ' }); RequestMethod = requestLineElements[0]; Resource = requestLineElements[1]; HttpVersion = requestLineElements[2]; Uri uri = new Uri(Resource); Host = uri.Host; Port = uri.Port; for (int i = 1; i < headers.Length; i++) { RequestHeaders += headers[i] + "\r\n"; } clientSock = sock; RequestBytes = requestBytesList.ToArray(); /* Console.WriteLine("Request method:" + RequestMethod); Console.WriteLine("Resource: " + Resource); Console.WriteLine("HttpVersion:" + HttpVersion); Console.WriteLine("Host: " + Host); Console.WriteLine("Request Headers: \n" + RequestHeaders); */ } 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