C# – Basic ClientHandler class – Using multi thread

This class is a new Thread launch by the Server class described in an other snippet.

class ClientHandler
 {
   private Socket socket;
   public Socket ClientSocket
   {
     get { return socket; }
     set { socket = value; }
   }

   private Stream stream;
   private StreamReader streamReader;
   private StreamWriter streamWriter;
   private Thread reader;

   public ClientHandler()
   {

   }

   public ClientHandler(Socket clientSocket): this()
   {
     this.socket = clientSocket;
   }

   public void start()
   {
     Console.WriteLine("New thread started; client is :" + socket.RemoteEndPoint);
     try
     {
       stream = new NetworkStream(socket);
       streamReader = new StreamReader(stream);
       streamWriter = new StreamWriter(stream);
       streamWriter.AutoFlush = true;

       reader = new Thread(startReading);
       reader.Start();
     }
     catch (Exception ex)
     {
       Console.WriteLine("Exception occured : " + ex.Message);
     }
   }

   private void startReading()
   {
     try
     {
       while (true)
       {

         string receivedString = streamReader.ReadLine();
         if (receivedString != null)
         {
           Console.WriteLine("A thread received : " + receivedString);
           streamWriter.WriteLine(receivedString);
         }
       }
     }
     catch (Exception ex)
     {
       Console.WriteLine("Exception occured : " + ex.Message);
     }
   }
 }
Advertisements

One thought on “C# – Basic ClientHandler class – Using multi thread

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s