using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace TcpServerStreamWriter
{
    class Program
    {
        public static void Main()
        {
            string data;
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 12537);
            Socket newsock = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            newsock.Bind(ipep);
            newsock.Listen(10);
            IPEndPoint localclient = (IPEndPoint) newsock.LocalEndPoint;
            Console.WriteLine("listening on {0} at port {1}", localclient.Address, localclient.Port);
            Console.WriteLine("Waiting for a client...");
            Socket client = newsock.Accept();
            IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
            Console.WriteLine("Connected with {0} at port {1}", newclient.Address, newclient.Port);

            NetworkStream ns = new NetworkStream(client);
            StreamReader sr = new StreamReader(ns);
            StreamWriter sw = new StreamWriter(ns);
            while (true)
            {
                try
                {
                    data = sr.ReadLine();
                    Console.WriteLine(data);
                    sw.WriteLine("ACK");
                    sw.Flush(); //mandatory
                }
                catch (IOException)
                {
                    break;
                }
              
            }
            Console.WriteLine("Disconnected from {0}", newclient.Address);
            sw.Close();
            sr.Close();
            ns.Close();
            Console.ReadKey();
        }
    }
}
