C#读取所有字节

时间:2014-03-17 20:50:40

标签: c# tcpclient networkstream

我正在尝试用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);
}

2 个答案:

答案 0 :(得分:10)

您未使用numberOfBytesRead。令我着迷的是,每个第二个TCP问题都有与其答案相同的问题。

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

答案 1 :(得分:7)

代码非常错误。 @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());
  }
}