My situation is this : I have a C# tcp socket through which I receive structured messages consisting of a 3 byte header and a variable size payload. The tcp data is routed through a network of tunnels and is occasionally susceptible to fragmentation. The solution to this is to perform a blocking read of 3 bytes for the header and a blocking read of N bytes for the variable size payload (the value of N is in the header). The problem I’m experiencing is that occasionally, the blocking receive operation returns a partial packet. That is, it reads a volume of bytes less than the number I explicitly set in the receive call. After some debugging, it appears that the number of bytes it returns is equal to the number of bytes in the Available property of the socket before the receive op.
This behavior is contrary to my expectation. If the socket is blocking and I explicitly set the number of bytes to receive, shouldn’t the socket block until it recv’s those bytes?, any help, pointers, etc would be much appreciated.
The behaviour depends on the type of socket you’re using. TCP is a Connection-Oriented Socket, which means:
When using TCP sockets, you have to be prepared for this possibility; check the return value of the
Receivemethod, and if it was less than what you expected,Receiveagain until either the socket is closed or you’ve actually received as much data as you need.