C # socket blocking behavior

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 payload. TCP data is routed through a network of tunnels and is sometimes prone to fragmentation. The solution to this is to implement a 3 byte read lock on the header and an N byte read lock on the variable size payload (the value of N is in the header). The problem I am facing is that sometimes the acquire lock operation will return a partial packet. That is, it reads less bytes than the number explicitly set in the receiving call. After some debugging, it seems that the number of bytes returned is equal to the number of bytes in the available socket property before op is received.

This behavior is contrary to my expectation. If the socket is blocking and I am explicitly setting the number of bytes to receive, shouldn't the socket block until it displays those bytes ?, any help, pointers, etc. Would be much appreciated.

+2


a source to share


1 answer


The behavior depends on the type of socket used. TCP is a connection oriented socket which means :

If you are using a connection-oriented Socket, the Receive method will read as much data as available, up to the number of bytes specified by the size parameter. If the remote host shuts down the Socket connection with the Shutdown method and all available data has been received, the Receive method will terminate immediately and return null bytes.



When using TCP sockets, you should be prepared for this opportunity; check the return value of the method Receive

, and if it was less than expected, Receive

again until the socket is closed or you actually got as much data as you need.

+2


a source







All Articles