简体   繁体   中英

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);
}

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 .

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());
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM