I wrote a client-server application where you just send messages to the server and it returns them in upper case. The problem is that the request and response are sent once, although everything is done in an infinite loop.
Customer:
namespace TcpClientApp { class Program { const int port = 8888; static string Addr = "127.0.0.1"; static void Main(string[] args) { Console.Write("Введите сове имя: "); string userName = Console.ReadLine(); TcpClient client = null; NetworkStream netStream = null; try { client = new TcpClient(Addr, port); netStream = client.GetStream(); while (true) { Console.Write(userName + ": "); // Ввод сообщения string message = Console.ReadLine(); // Преобразуем сообщение в массив байтов byte[] data = Encoding.UTF8.GetBytes(message); // Отправка сообщения netStream.Write(data, 0, data.Length); // Получаем ответ data = new byte[64]; StringBuilder strB = new StringBuilder(); int bytes = 0; do { bytes = netStream.Read(data, 0, data.Length); strB.Append(Encoding.UTF8.GetString(data, 0, bytes)); } while (netStream.DataAvailable); message = strB.ToString(); Console.WriteLine(DateTime.Now.ToShortTimeString() + ": " + message); } } catch (Exception exc) { Console.WriteLine(exc.Message); } finally { client.Close(); Console.ReadLine(); } } } } Server:
namespace TcpServerApp { class Program { const int port = 8888; static void Main(string[] args) { Console.WriteLine("Server started at " + DateTime.Now.ToShortTimeString()); TcpListener listener = null; TcpClient client = null; NetworkStream netStream = null; try { IPAddress localAddr = IPAddress.Parse("127.0.0.1"); listener = new TcpListener(localAddr, port); // Запуск слушателя listener.Start(); while (true) { // Получаем входящее подключение client = listener.AcceptTcpClient(); // Получаем сетевой поток для чтения и записи netStream = client.GetStream(); // Читаем запрос от клиента byte[] data = new byte[64]; StringBuilder strB = new StringBuilder(); int bytes = 0; do { bytes = netStream.Read(data, 0, data.Length); strB.Append(Encoding.UTF8.GetString(data)); } while (netStream.DataAvailable); string message = strB.ToString(); Console.WriteLine(message); message = message.ToUpper(); data = Encoding.UTF8.GetBytes(message); netStream.Write(data, 0, data.Length); } } catch (Exception exc) { Console.WriteLine(exc.Message); } finally { if (netStream != null) netStream.Close(); if (client != null) client.Close(); } } } } Tell me, please, what was done wrong?
netStream.Read(data, 0, data.Length);- this is not true. You must read the data in a loop before the arrival of the required amount. - VladD