using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace TcpServeurExemple
{
    class TcpServeurSimple1
    {
        static void Main()
        {
            Console.WriteLine("lancement serveur");
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            TcpListener server = new TcpListener(ipAddress, 10000);
            server.Start();
            Console.WriteLine("\n Attente connection... ");

            TcpClient client = server.AcceptTcpClient();//waiting fort client connection
            using (NetworkStream ns = client.GetStream()) // client connected so get the stream
            {
                Encoding encode = Encoding.UTF8;
                byte[] byteBuffer = new byte[100]; //allocate reception buffer

                // read and loop until all bytes read or connection closed
                int totalBytesRcvd = 0; // Total bytes received so far
                int bytesRcvd; // Bytes received in last read
                while (totalBytesRcvd < byteBuffer.Length)
                {
                    if ((bytesRcvd = ns.Read(byteBuffer, totalBytesRcvd,
                                       byteBuffer.Length - totalBytesRcvd)) == 0)
                    {
                        break;
                    }
                    totalBytesRcvd += bytesRcvd;
                }
                string strRequete = encode.GetString(byteBuffer); // convert byte to string
                Console.WriteLine("message du client  " + strRequete);
                byte[] reponse = encode.GetBytes("ACK"); // response to client
                byte[] txBuffer = new byte[10];
                reponse.CopyTo(txBuffer, 0);
                ns.Write(txBuffer, 0, txBuffer.Length); // write send all byte to stream
                Console.WriteLine("\n Fin serveur... ");
                Console.ReadKey();
            }// end of using imply closing connection

        }
    }
}
