Search code examples
c#tcpclientnetworkstream

C# read all bytes


I am trying to write a simple client/server application in C#. The following is an example server reply sent to my client:

reply {20}<entry name="test"/>

where {20} indicates number of chars that full reply contains. In the code I wrote below how can I use this number to loop and read ALL chars?

TcpClient tcpClient = new TcpClient(host, port);

NetworkStream networkStream = tcpClient.GetStream();

...

// Server Reply
if (networkStream.CanRead)
{
    // Buffer to store the response bytes.
    byte[] readBuffer = new byte[tcpClient.ReceiveBufferSize];

    // String that will contain full server reply
    StringBuilder fullServerReply = new StringBuilder();

    int numberOfBytesRead = 0;

    do
    {
        numberOfBytesRead = networkStream.Read(readBuffer, 0, readBuffer.Length);
        fullServerReply.AppendFormat("{0}", Encoding.UTF8.GetString(readBuffer, 0, tcpClient.ReceiveBufferSize));
    } while (networkStream.DataAvailable);
}

Solution

  • You're not using numberOfBytesRead. It is fascinating to me that every 2nd TCP question has this same issue as its answer.

    Apart from that, you cannot split UTF-8 encoded string at arbitrary boundaries. Encoding.UTF8.GetString will return garbage. Use StreamReader.