本文介绍了C#读取所有字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"/>

其中{20}表示完整答复包含的字符数.在下面编写的代码中,如何使用该数字循环并读取所有字符?

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

推荐答案

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

You're not using numberOfBytesRead. It is fascinating to me that every 2nd TCP question has this same issue as its answer.

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

Apart from that, you cannot split UTF-8 encoded string at arbitrary boundaries. Encoding.UTF8.GetString will return garbage. Use StreamReader.

这篇关于C#读取所有字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-26 08:37