C#读取所有字节

本文关键字:字节 读取 | 更新日期: 2023-09-27 17:50:37

我正在尝试用C#编写一个简单的客户端/服务器应用程序。以下是发送给我的客户端的服务器回复示例:

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

其中{20}表示完整回复包含的字符数。在我下面写的代码中,我如何使用这个数字循环并读取所有字符?

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

C#读取所有字节

您没有使用numberOfBytesRead。让我着迷的是,每一个第二个TCP问题都有相同的问题作为答案。

除此之外,您不能在任意边界处拆分UTF-8编码的字符串。Encoding.UTF8.GetString将返回垃圾。使用StreamReader

代码就是大错特错@usr已经指出了两个重大错误。

这是更正后的代码:

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