我正在尝试用 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);
}
最佳答案
您没有使用 numberOfBytesRead
。令我着迷的是,每个第 2 个 TCP 问题的答案都与此相同。
除此之外,您不能在任意边界处拆分 UTF-8 编码的字符串。 Encoding.UTF8.GetString
将返回垃圾。使用 StreamReader
。
关于C#读取所有字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22465102/