http://www.java2s.com/Tutorial/CSharp/0580__Network/ThreadPoolbasedTcpserver.htm
ThreadPool based Tcp server
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class MainClass
{
public static void Main()
{
TcpListener client = new TcpListener(9050);
client.Start();
Console.WriteLine("Waiting for clients...");
while(true)
{
while (!client.Pending())
{
Thread.Sleep(1000);
}
ConnectionThread newconnection = new ConnectionThread(client);
}
}
}
class ConnectionThread
{
public TcpListener threadListener;
public ConnectionThread(TcpListener lis){
threadListener = lis;
ThreadPool.QueueUserWorkItem(new WaitCallback(HandleConnection));
}
public void HandleConnection(object state)
{
int recv;
byte[] data = new byte[1024];
TcpClient client = threadListener.AcceptTcpClient();
NetworkStream ns = client.GetStream();
string welcome = "Welcome";
data = Encoding.ASCII.GetBytes(welcome);
ns.Write(data, 0, data.Length);
while(true)
{
data = new byte[1024];
recv = ns.Read(data, 0, data.Length);
ns.Write(data, 0, recv);
}
ns.Close();
client.Close();
}
}
http://www.java2s.com/Tutorial/CSharp/0420__Thread/UseThreadPooltoimplementahelloserver.htm
20.28.5.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 );
}
}
}
}