Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

tcpclient - 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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...