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

namespace TcpClient
{
    class TcpClientSimple
    {
        static void Main()
        {
            Console.WriteLine("lancement client");
            System.Net.Sockets.TcpClient monTcpClient = new System.Net.Sockets.TcpClient("127.0.0.1", 10000);
            using (NetworkStream ns = monTcpClient.GetStream())
            {
                string requete = "LED ON";
                Encoding encode = Encoding.UTF8;
                byte[] stringEncoded = encode.GetBytes(requete); // fill buffer with encoded string
                byte[] txBuffer = new byte[100];
                stringEncoded.CopyTo(txBuffer,0);
                ns.Write(txBuffer, 0, txBuffer.Length); // send to server (as write send all byte no loop needed) 
                Console.WriteLine("envoi de la requete de TAILLE FIXE");

                Console.WriteLine("attente reponse serveur");
                byte[] rxBuffer = new byte[10];
                // 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 < rxBuffer.Length)
                {
                    if ((bytesRcvd = ns.Read(rxBuffer, totalBytesRcvd,
                                       rxBuffer.Length - totalBytesRcvd)) == 0)
                    {
                        break;
                    }
                    totalBytesRcvd += bytesRcvd;
                }
  
                string stringResponse = encode.GetString(rxBuffer);
                Console.WriteLine(stringResponse);
                Console.WriteLine("fin");
                Console.ReadKey();
            }
        }
    }
}
