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)
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/Writecalls, 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:
If you want to read all data in a blocking way you can use loop until
DataAvailableistruebut a subsequent call toReadreturns0. (Hope I remembered that part correctly, haven’t done any network programming in a while)