You do not think that Socket.Receive
reads less bytes very well than the length of the provided buffer. The return value tells you the number of bytes that were actually read. I see that you correctly store this value in a variable, but I do not see any code that uses it.
You must be prepared to make several Receive
calls to receive the entire packet. In particular, when you receive packet data.
I am not sure if this is the cause of your problem. But this may be so, since a short delay on the client side may be enough to fill the network buffers so that the entire packet is read in one call.
Try using the following code to extract package data:
int bufferPos = 0; while (bufferPos < responseBuffer.Length) { bufferPos += socket.Receive(responseBuffer, bufferPos, responseBuffer.Length - bufferPos, SocketFlags.None); }
Note. You should also support the case when the first Receive
call (the one where you get the packet data length) does not return 4 bytes.
source share