A stream that has separate read and write positions

I want to emulate a network type stream on one PC.

I did this by creating a Stream that uses 2 basic streams, one for reading and another for writing.

Then I create 2 instances of this class by swapping 2 threads. I am currently using MemoryStream as 2 main streams.

Now the problem is that if I write X bytes to a MemoryStream , then its position will be X, and if I do a Read , I will not receive any data, since I am at the end of the stream.

Given that I usually do a couple of reads / writes (so it can't just reset postion to 0 after each write) , what can Stream use to get this behavior?

In fact, I want to have some byte queue to which I can write and read as a stream.

i.e. (ignoring the actual arguments of the method)

 MyStream.Write({ 1, 2, 3, 4, 5, 6 }); MyStream.Write({ 7, 8 }); MyStream.Read(3) // Returns { 1, 2, 3 } MyStream.Read(4) // Returns { 4, 5, 6, 7 } 
+7
source share
1 answer

This is actually a lot easier than I thought (anyway).
I simply restore / write read / write positions before performing any operation:

 public class QueueStream : MemoryStream { long ReadPosition; long WritePosition; public QueueStream() : base() { } public override int Read(byte[] buffer, int offset, int count) { Position = ReadPosition; var temp = base.Read(buffer, offset, count); ReadPosition = Position; return temp; } public override void Write(byte[] buffer, int offset, int count) { Position = WritePosition; base.Write(buffer, offset, count); WritePosition = Position; } } 
+8
source

All Articles