❔ Receive data from tcp client by one

Hello, the code is below, the problem is that the data is wrote only when the client disconnects, which is not correct
            TcpListener listener = new(8080);
            listener.Start();
            while (true)
            {
                Debug.WriteLine("Waiting for client...");

                // Accept an incoming client connection
                TcpClient client = await listener.AcceptTcpClientAsync();
                Debug.WriteLine("Client connected!");
                NetworkStream stream = client.GetStream();
                StreamReader reader = new StreamReader(stream, Encoding.UTF8);

                // Read data from the client
                while (client.Connected)
                {
                    string? data = await reader.ReadLineAsync();
                    if (data == null) break;
                    Debug.WriteLine("Received data: " + data);
                }
                client.Close();
                Debug.WriteLine("Client disconnected.");
            }
Was this page helpful?