www.pudn.com > HttpProxy.rar > ProxyServer.cs


using System; 
using System.IO; 
using System.Net; 
using System.Text; 
using System.Collections; 
using System.Threading; 
using System.Net.Sockets; 
 
namespace HttpProxy.Component 
{ 
	///  
	/// ProxyServer 类 
	///  
	public class ProxyServer:IDisposable 
	{ 
		private int listenCount; 
		private int port; 
		private Socket server; 
		private bool disposed = false; 
	 
		internal static LogDataset dsLog=new LogDataset(); 
		internal static ArrayList arrThread=new ArrayList();//container for thread 
 
		///  
		/// Initializes a new instance of the  class. 
		///  
		public ProxyServer() 
		{			 
		}		 
 
		///  
		/// Starts this instance. 
		///  
		public void Start() 
		{ 
			server=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); 
			IPEndPoint iep=new IPEndPoint(IPAddress.Any,this.Port); 
			server.Bind(iep); 
			server.Listen(this.ListenCount); 
			dsLog.Tables["Parent"].Rows.Add(new object[]{null,"主线程,监听:",port,DateTime.Now}); 
			server.BeginAccept(new AsyncCallback(AcceptRequest),server);			 
		} 
 
		///  
		/// Accepts the request. 
		///  
		/// The iar. 
		private void AcceptRequest(IAsyncResult iar) 
		{ 
			Socket oldserver=(Socket)iar.AsyncState; 
			Socket client=oldserver.EndAccept(iar); 
 
			Proxy proxy = new Proxy(client); 
			Thread thread = new Thread(new ThreadStart(proxy.Run));			 
			arrThread.Add(thread); 
			thread.Start(); 
 
			server.BeginAccept(new AsyncCallback(AcceptRequest),server); 
		} 
 
		///  
		/// Gets or sets the listen count. 
		///  
		/// The listen count. 
		public int ListenCount 
		{ 
			get 
			{ 
				return this.listenCount; 
			} 
			set 
			{ 
				this.listenCount=value; 
			} 
		} 
 
		///  
		/// Gets or sets the port. 
		///  
		/// The port. 
		public int Port 
		{ 
			get 
			{ 
				return this.port; 
			} 
			set 
			{ 
				this.port=value; 
			} 
		} 
 
		#region IDisposable 成员 
 
		public void Dispose() 
		{ 
			Dispose(true); 
			GC.SuppressFinalize(this); 
		} 
 
		private void Dispose(bool disposing) 
		{ 
			if(!this.disposed) 
			{ 
				// If disposing equals true, dispose all managed  
				// and unmanaged resources. 
				if(disposing) 
				{ 
					// Dispose managed resources. 
					server.Close(); 
				}        
			} 
			disposed = true; 
 
		} 
 
		~ProxyServer() 
		{ 
			Dispose(false); 
		} 
 
		#endregion 
	} 
}