Public partial class comservice {
Private int maxlink = 100000;
Private int currentlinked;
Private manualresetevent tcpclientconnected = new manualresetevent (false );
Public void start (){
Thread = new thread (new parameterizedthreadstart (showstat ));
Thread. isbackground = true;
Thread. start ();
Tcplistener server = new tcplistener (new system.net. ipendpoint (0, 8090 ));
Server. start (100 );
Tcpclientconnected. reset ();
Iasyncresult result = server. beginaccepttcpclient (new asynccallback (acceptor), server );
Tcpclientconnected. waitone ();
}
Private void showstat (object o ){
While (true ){
Lock (typeof (comservice )){
Console. writeline ("current connections:" + currentlinked + "/" + maxlink );
}
Thread. sleep (2000 );
}
}
Private void acceptor (iasyncresult o ){
Tcplistener server = o. asyncstate as tcplistener;
Debug. assert (server! = Null );
Tcpclient client = null;
Try {
Client = server. endaccepttcpclient (o );
System. threading. interlocked. increment (ref currentlinked );
} Catch {
}
Iasyncresult result = server. beginaccepttcpclient (new asynccallback (acceptor), server );
If (client = null ){
Return;
} Else {
Thread. currentthread. join ();
}
Close (client );
}
Private void close (tcpclient client ){
If (client. connected ){
Client. client. shutdown (socketshutdown. both );
}
Client. client. close ();
Client. close ();
System. threading. interlocked. decrement (ref currentlinked );
}
}
}
The following is the client code:
Public class clientpool {
Private static list <tcpwork> clients = new list <tcpwork> ();
Private static int freecount;
Private static int workcount;
Private static int maxallowed = 2;
Private static int minclients = 2;
/// <Summary>
/// Create new instance
/// </Summary>
Private clientpool (){
}
Private static clientpool instance;
Private static readonly object syncinstanceobj = new object ();
Public static clientpool singleton {
Get {
If (instance = null ){
Lock (syncinstanceobj ){
If (instance = null ){
Instance = new clientpool ();
}
}
}
Return instance;
}
}
Private static readonly object syncobj = new object ();
Public tcpwork getclient (){
Try {
Tcpwork work = new tcpwork ();
Work. connect ("127.0.0.1", 8090 );
Work. lingerstate = new lingeroption (false, 3 );
Work. iswork = true;
Work. expired = false;
Workcount ++;
Lock (syncobj ){
Clients. add (work );
}
Console. writeline (workcount );
Return work;
} Catch (exception ex ){
Console. writeline (ex. message );
Return null;
}
}
}
The client simulates multi-thread concurrency
Class program {
Static void main (string [] args ){
For (int I = 0; I <1000; I ++ ){
Threadpool. queueuserworkitem (new waitcallback (work), null );
}
Console. readkey ();
}
Private static void work (object o ){
Clientpool. singleton. getclient ();
}
}