Tcp server based on Thread : Socket Server : Network C# Examples


C# Examples » Network » Socket Server »

 

Tcp server based on Thread









    
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(10000);
                  }
                  ConnectionThread  newconnection  =  new  ConnectionThread(client);
            }
      }
}

class  ConnectionThread
{
      TcpListener  threadListener;

      public  ConnectionThread(TcpListener  lis){
            threadListener  =  lis;
            Thread  newthread  =  new  Thread(new  ThreadStart(HandleConnection));
            newthread.Start();
      }
      
      public  void  HandleConnection()
      {
            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];
                  int  recv  =  ns.Read(data,  0,  data.Length);
                  if  (recv  ==  0)
                        break;
                  ns.Write(data,  0,  recv);
            }
            ns.Close();
            client.Close();
      }
}
    
   
  
   




HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Network
» Socket Server