Ошибка во врем выполнения TCP приложения со стороны клиента

В процессе работы приложения на начальном этапе происходит взаимная отправка строки как с сервера клиенту так и от клиента серверу. Приложение не работает согласно задуманной логике: происходит зависание на этапе считывания данных. Клиент преждевременно завершает работу несмотря на вложенный бесконечный цикл. Сервер не обрабатывает данные, но продолжает функционировать. Код ниже Сервер

namespace server
{
    internal class Server
    {
        TcpListener server = new TcpListener(new IPAddress(new byte[] { 127, 0, 0, 1 }) , 21419);
        List<TcpClient> clients = new List<TcpClient>();

        public void Start()
        {
            Thread thread = new Thread(new ThreadStart(StartServer));
            thread.Start();
        }
        public void StartServer() 
        { 
            try
            {
                server.Start();
                Console.WriteLine("Server has launched and waiting for connections");
                while (true)
                {
                    TcpClient client = server.AcceptTcpClient();
                    clients.Add(client);
                    Task.Run( () =>  ProcessClient(client));
                    Task.Delay(100).Wait();
                }
                server.Stop();

            }
            catch (Exception ex)
            {
                server.Stop();

                Console.WriteLine(ex.ToString());
            }
            finally
            {

            }

        }

        public async Task ProcessClient(TcpClient client)
        {
            try
            {
                Console.WriteLine("Дошли до стадии обработки");
                byte[] buffer = new byte[1024];
                int byteCount;
                using NetworkStream stream = client.GetStream();
                using MemoryStream ms = new MemoryStream();
                stream.Write(Encoding.Unicode.GetBytes("*********************************"));
                while (client.Connected)
                {
                    do
                    {
                        byteCount = await stream.ReadAsync(buffer);
                        ms.Write(buffer);
                    } while (byteCount > 0);
                    // допустим считали данные дальше преобразуем
                    string message = Encoding.Unicode.GetString(ms.ToArray());
                    Console.WriteLine("Получено собщение: " +  message);
                    DoSmth(message);
                    Task.Delay(100).Wait();
                }
                if (!client.Connected) Console.WriteLine("Соединение разорвано");
                client.Close();
                clients.Remove(client);
                return;

            }
            catch (SocketException ex)
            {
                client.Close();
                clients.Remove(client);

                Console.WriteLine(ex.ToString());
                return ;

            }
            finally
            {
            }
        }

        public void DoSmth(string mess)
        {
            using FileStream fs = new FileStream("result.txt", FileMode.OpenOrCreate);
            using StreamWriter writer = new StreamWriter(fs);
            writer.WriteLine(mess);
            writer.Close();
            fs.Close();
        }
        public void SendToAll()
        {

        }
        public Server() { }
    }
}

Клиент

namespace client
{
    internal class Client
    {
        IPEndPoint IPaP = new IPEndPoint(new IPAddress(new byte[] {127,0,0,1}), 21419);
        TcpClient client;

        Thread th;
        public void Start() 
        {
            th = new Thread(new ThreadStart(StartClient));
            th.Start();
        }
        private void StartClient()
        {
            try
            {
                client = GetConnection(IPaP);
                if(client == null)
                {
                    return;
                }
                else
                {
                    Task.Factory.StartNew(() => ProcessClient()); //автозакрытие
                    //ProcessData(); //бессконечная загрузка на второй итерации обработки входящего сообщения
                }
            }
            catch (Exception ex) 
            { 
                Console.WriteLine(ex.Message + " " + ex.ToString());
            }
            finally 
            { 
            
            }
        }

        private async void ProcessClient()
        {
            try
            {
                int byteRecived = 0;
                byte[] buffer = new byte[1024];
                using NetworkStream stream = client.GetStream();
                using MemoryStream ms = new MemoryStream();
                stream.WriteAsync(Encoding.Unicode.GetBytes("*********************************"));
                Console.WriteLine("Дошли до стадии обработки");

                while (client.Connected)
                {
                    do
                    {
                        Console.WriteLine("1byte recived: " + byteRecived);

                        byteRecived = await stream.ReadAsync(buffer);
                        ms.Write(buffer);
                        Console.WriteLine("2byte recived: " + byteRecived);
                    } while (byteRecived > 0);
                    string message = Encoding.Unicode.GetString(ms.ToArray());
                    Console.WriteLine("1Сообщение: " + message);

                    DoSmth(message);
                    ms.Flush();
                    Console.WriteLine("2Сообщение: " + message);

                    Task.Delay(100).Wait();
                }
                Console.WriteLine("Статус соединения: " + client.Connected);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        
        public void DoSmth(string mess)
        {
            Console.WriteLine("Записываем в файл");

            using FileStream fs = new FileStream("result.txt", FileMode.OpenOrCreate);
            using StreamWriter writer = new StreamWriter(fs);
            writer.WriteLine(mess);
            writer.Close();
            fs.Close();
        }

        private TcpClient GetConnection(IPEndPoint ip)
        {
            TcpClient client = new TcpClient();

            DateTime dt = DateTime.Now;
            while (!client.Connected && (DateTime.Now).Subtract(dt).Seconds < 5)
            {
                client.Connect(ip);
                Task.Delay(100).Wait();
            }
            if (client.Connected != true)
            {
                return null;
            }
            else
            {
                return client;
            }
        }

        public Client() { }
    }
}

Результат выполнения программы


Ответы (0 шт):