日期:2014-05-18 浏览次数:21116 次
using System; using System.Net; using System.Net.Sockets; using System.Threading; namespace LocalProxy { class Program { static void Main(string[] args) { const int DEFPORTNUM = 8080; 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,port2use); Thread rhThread = new Thread(new ThreadStart(rh.DoRequest)); rhThread.Start(); Console.WriteLine(rh.Response); } } } }
using System; using System.Net; using System.Net.Sockets; namespace LocalProxy { public class RequestHandler { public RequestHandler(string host, int port, string httpVersion, string resource, string requestMethod, string requestHeaders) { Host = host; Port = port; HttpVersion = httpVersion; Resource = resource; RequestMethod = requestMethod; RequestHeaders = requestHeaders; } // RequestHandler public RequestHandler(Socket sock,int port) { System.Text.Encoding utf8 = System.Text.Encoding.UTF8; // Get the HTTP headers first string header = ""; while (true) { byte[] bytes = new byte[1]; int bytesRec = sock.Receive(bytes); header += System.Text.Encoding.ASCII.GetString(bytes, 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[] { ' ' }); Port = port; RequestMethod = requestLineElements[0]; Resource = requestLineElements[1]; HttpVersion = requestLineElements[2]; Host = getHost(Resource); for (int i = 1; i < headers.Length; i++) { RequestHeaders += headers[i] + "\r\n"; } /* Console.WriteLine("Request method:" + RequestMethod); Console.WriteLine("Resource: " + Resource); Console.WriteLine("HttpVersion:" + HttpVersion); Console.WriteLine("Host: " + Host); Console.WriteLine("Request Headers: \n"