reassembly problem of fragmented messages


  • HI

    There are TCP client and TCP server. The long messages from client are fragmented upto 536 bytes. The server treats (reassembly) them correctly in 99.99% cases. But it does not work properly in some cases. It means Socket.Receive returns the 1st fragment into buffer array only. The length of buffer is defined from Socket.Available.

    Please help me to find the answers for following question :
    - Why the 2nd frame is not taken into consideration?
    - How to force the socket to reassemble the fragmented message correctly?

    Thank you in advice.
    Friday, October 09, 2009 4:49 PM

All replies

  • TCP is a reliable protocol.  You shouldn't be able to get incorrectly assembled data...

    However, maybe what you are saying is that you are getting all of the data, just in more pieces than you would like.  You do not have control over this because TCP is a stream protocol.  You need to deal with it properly regardless of whether Receive returns one byte at a time or n bytes at a time.  Receive is non-blocking so long as at least one byte is available.

    Consider constructing a BinaryReader on top of a NetworkStream that you construct on top of the Socket.  The BinaryReader.ReadBytes method will perform a blocking read for the number of bytes you request.  (Alternatively, call Socket.Receive in a loop to fill the buffer to the expected number of bytes.)

    See the following FAQ from Stephen Cleary for good information on this issue: http://nitoprograms.blogspot.com/2009/04/message-framing.html

    Friday, October 09, 2009 11:47 PM