Thread Pool Tcp Server : Thread Pool « Thread « C# / C Sharp

Home
C# / C Sharp
1.2D Graphics
2.Class Interface
3.Collections Data Structure
4.Components
5.Data Types
6.Database ADO.net
7.Date Time
8.Design Patterns
9.Development Class
10.Event
11.File Stream
12.Generics
13.GUI Windows Form
14.Internationalization I18N
15.Language Basics
16.LINQ
17.Network
18.Office
19.Reflection
20.Regular Expressions
21.Security
22.Services Event
23.Thread
24.Web Services
25.Windows
26.Windows Presentation Foundation
27.XML
28.XML LINQ
C# Book
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source
C# / C Sharp » Thread » Thread PoolScreenshots 
Thread Pool Tcp Server

/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class ThreadPoolTcpSrvr
{
   private TcpListener client;

   public ThreadPoolTcpSrvr()
   {
      client = new TcpListener(9050);
      client.Start();

      Console.WriteLine("Waiting for clients...");
      while(true)
      {
         while (!client.Pending())
         {
            Thread.Sleep(1000);
         }
         ConnectionThread newconnection = new ConnectionThread();
         newconnection.threadListener = this.client;
         ThreadPool.QueueUserWorkItem(new
                    WaitCallback(newconnection.HandleConnection));
      }
   }

   public static void Main()
   {
      ThreadPoolTcpSrvr tpts = new ThreadPoolTcpSrvr();
   }
}

class ConnectionThread
{
   public TcpListener threadListener;
   private static int connections = 0;

   public void HandleConnection(object state)
   {
      int recv;
      byte[] data = new byte[1024];

      TcpClient client = threadListener.AcceptTcpClient();
      NetworkStream ns = client.GetStream();
      connections++;
      Console.WriteLine("New client accepted: {0} active connections",
                         connections);

      string welcome = "Welcome to my test server";
      data = Encoding.ASCII.GetBytes(welcome);
      ns.Write(data, 0, data.Length);

      while(true)
      {
         data = new byte[1024];
         recv = ns.Read(data, 0, data.Length);
         if (recv == 0)
            break;
      
         ns.Write(data, 0, recv);
      }
      ns.Close();
      client.Close();
      connections--;
      Console.WriteLine("Client disconnected: {0} active connections",
                         connections);
   }
}

           
       
Related examples in the same category
1.ThreadPool.RegisterWaitForSingleObject
2.ThreadPool.QueueUserWorkItem
3.Thread pool demoThread pool demo
4.illustrates the use of the system thread poolillustrates the use of the system thread pool
5.Thread Pool SampleThread Pool Sample
w__w___w._j__a_v_a___2_s___.__c_o__m_ | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.