Question

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);
}
Was it helpful?

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.

OTHER TIPS

The code is just horribly wrong. @usr already pinpointed two big mistakes.

Here is corrected code:

// Server Reply
if (networkStream.CanRead) {
  // Buffer to store the response bytes.
  byte[] readBuffer = new byte[tcpClient.ReceiveBufferSize];
  string fullServerReply = null;
  using (var writer = new MemoryStream()) {
    while (networkStream.DataAvailable) {
      int numberOfBytesRead = networkStream.Read(readBuffer, 0, readBuffer.Length);
      if (numberOfBytesRead <= 0) {
        break;
      }
      writer.Write(readBuffer, 0, numberOfBytesRead);
    }
    fullServerReply = Encoding.UTF8.GetString(writer.ToArray());
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top