armin
armin

Reputation: 2025

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)

Upvotes: 2

Views: 892

Answers (5)

MarcF
MarcF

Reputation: 3299

I think the answers already here respond to your specific question quite well, but possibly more generally: If you are trying to send data over a networkStream object for the purposes of network communication check out the open source library, networkComms.net.

Upvotes: 0

CodesInChaos
CodesInChaos

Reputation: 108810

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)

Upvotes: 7

CloudyMarble
CloudyMarble

Reputation: 37566

Read the Documentation:

This method reads data into the buffer parameter and returns the number of bytes successfully read. If no data is available for reading, the Read method returns 0. The Read operation reads as much data as is available, up to the number of bytes specified by the size parameter. If the remote host shuts down the connection, and all available data has been received, the Read method completes immediately and return zero bytes.

So it could be because of connection failure that you get each time different number, anyway you can check the result to know if its the reason.

Upvotes: 1

M4N
M4N

Reputation: 96571

From MSDN:

The Read operation reads as much data as is available, up to the number of bytes specified by the size parameter.

I.e. you have to call the Read() method in a loop until you received all data. Have a look at the sample code in MSDN.

Upvotes: 2

Strillo
Strillo

Reputation: 2972

You need to loop reading bytes from the message until the Available property on the TCP client or the DataAvailable property of the NetworkStream are 0 (= no more bytes left)

Upvotes: 1

Related Questions