Valmorgal
Valmorgal

Reputation: 109

Processing messages from a byte[] buffer, prepending leftover bytes to the next buffer

I have a byte array of 256 (byte[256]) and I have a stream of byte data coming in which I am reading with the 256 Buffer size on my byte array.

I parse the byte array and extract 2 "Messages" from the byte array...leaving 13 bytes in the array un-processed.

Question how do I get the 13 bytes attached to the next 256 byte array that comes in so I can process the "partial bytes" from the first byte array with the second byte array in the fastest possible way?

Example:

    [256 Array]
    [+++++++++++++++++++] (1st Buffer)
    [**************] (Processed in the first iteration...)
                   [----] (Remaining from the 1st Buffer)
                   [----][++++++++++++++++++++](Old Buff + New Buff256[])
                   [-----+++++++++++++++++++++] <---- (THIS)
                  (How do I get this Combination to process in the most
                  efficient manner so I am not missing messages that may
                  have been chopped off by my buffer size from the old buffer)

Thanks in advance guys.

Upvotes: 2

Views: 421

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103467

Declare a buffer of 512 bytes instead of 256.

When you are ready to receive another 256 bytes, check if you have any left-overs in the buffer. If you do, copy them to the start of the buffer.

Then receive your 256 bytes, putting them after the left-overs.

Assuming your messages are all smaller than 256 bytes each, you shouldn't overrun your buffer.

Upvotes: 3

Related Questions