Search code examples
c#tcpclientnetworkstream

NetworkStream.Read() produce repetitive bytes when reading in loop


I'm reading all DataAvailablefrom NetworkStream in a while loop and in every cycle I'm reading available data with a specific chunk size:

TcpClient client = new TcpClient("server address", 23);
NetworkStream stream = client.GetStream();

byte[] data = new byte[2048]; // read in chunks of 2KB
int bytesRead;
string output = "";

do
{
    bytesRead = stream.Read(data, 0, data.Length);
    output += System.Text.Encoding.ASCII.GetString(data, 0, data.Length);
} while (stream.DataAvailable);

return output;

Problem is in output I get some random texts from middle of my received bytes, I mean something similar to this:

1 A
2 B
3 C
4 D
5 E
6 F
7 G
8 H
9 I
10 J //here my output must finish but random bytes from middle append to the end:
3 C //repetitive bytes
4 D //repetitive bytes
5 E //repetitive bytes

What makes me confused is that if I increase chunk size from 2048 to 3072 this problem will not happen.

I also traced TcpClient.Available with a breakpoint in each cycle:

First cycle -> 4495
Second cycle -> 2447
Third cycle -> 399
Forth cycle -> 0

Solution

  • I would have thought that this:

    output += System.Text.Encoding.ASCII.GetString(data, 0, data.Length);
    

    should be this:

    output += System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);
    

    That ensures that only data read on this specific occasion will be included in the output.