My app reads bytes from a TCP socket and needs to buffer them up, so that I can extract messages from them later. Due to the nature of TCP I may get partial or multiple messages in one read, so after each read I would like to inspect the buffer and extract as many full messages as are available.
Therefore I want a class that allows me to do the following:
- append arbitrary byte[] data to it
- inspect the content without consuming it, in particular checking the amount of content and also searching for the existence of a certain byte or bytes
- extract and consume part of the data as a byte[], while leaving the rest in there for a future read
I expect that what I want can be done with 1 or more existing classes in the .NET library, but I’m not sure which ones. System.IO.MemoryStream looks close to what I want, but (a) it isn’t clear whether it’s suited to being used as a buffer (does the read data get removed from the capacity?) and (b) reads and writes seem to happen at the same place – “The current position of a stream is the position at which the next read or write operation could take place.” – which is not what I want. I need to be writing to the end and reading from the front.
Just use a big byte-array and Array.Copy – it should do the trick.
If not, use
List<byte>.If you use the array you have to implement an index to it (where you copy additional data) yourself (same for checking the content-size), but it’s straightforward.
If you are interested: here is a simple implementation of a “cyclic buffer”. The test should run (I threw a couple unit test at it, but it didn’t check all critical path):
Please note: the code “consumes” on read – if you don’t want that just remove the “_startIndex = …” parts (or make a overload optional parameter and check or whatever).