Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - clientStream.Read returns wrong number of bytes

This code works:

TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[5242880];
int bytesRead;

bytesRead = clientStream.Read(message, 0, 909699);

But this returns the wrong number of bytes:

bytesRead = clientStream.Read(message, 0, 5242880);

Why? How can I fix it?

(the real data size is 1475186; the code returns the 11043 as the number of bytes)

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

If this is a TCP based stream, then the answer is that the rest of the data simply didn't arrive yet.

TCP is stream oriented. That means there is no relation between the number of Send/Write calls, and the number of receive events. Multiple writes can be combined together, and single writes can be split.

If you want to work with messages on TCP, you need to implement your own packeting algorithm on top of it. Typical strategies to achieve this are:

  1. Prefix each packed by its length, usual with binary data
  2. Use a separation sequence such as a line-break. Usual with text data.

If you want to read all data in a blocking way you can use loop until DataAvailable is true but a subsequent call to Read returns 0. (Hope I remembered that part correctly, haven't done any network programming in a while)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...