C# – Basic Server class – Using TCPListener

A basic server in C#

See ClientHandler

class Server
{
 private const int local_port = 5000;
 private TcpListener listener;

 public void start()
  {
   listener = new TcpListener( local_port);
   listener.Start();
   Console.WriteLine("Server started; listening on port " + local_port);

   while (true)
   {
     Socket clientSocket = listener.AcceptSocket();
     Console.WriteLine("Client connected : " + clientSocket.RemoteEndPoint);

     ClientHandler clientHandler = new ClientHandler(clientSocket);
     Thread clientThread = new Thread(clientHandler.start);
     clientThread.Start();
   }
  }
 }
Advertisements

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);
     }
   }
 }