Mega Code Archive

 
Categories / C# Tutorial / Thread
 

Use ThreadPool to implement a hello server

using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; class MainClass {   static void serve( Object obj )   {     using ( Socket s = (Socket)obj )     {       Encoding enc = Encoding.GetEncoding( "ASCII" );       Byte[] buff = enc.GetBytes( "hello" );       s.Send( buff );       s.Shutdown( SocketShutdown.Both );       s.Close();     }   }   [STAThread]   static void Main(string[] args)   {     using ( Socket svr = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ) )     {       svr.Bind( new IPEndPoint( IPAddress.Loopback, 8888 ) );       svr.Listen( 5 );       while ( true ) {         Socket req = svr.Accept();         ThreadPool.QueueUserWorkItem( new WaitCallback( serve ), req );       }     }   } }