0

Is there any possibility for making BsonBinaryReader accept a nonseekable stream e.g. NetworkStream?

So I don't have to save all the data persistently and afterward start parsing it via BsonBinaryReader but can instead happen on the fly?

Example:

var response = new NetworkStream(MAGIC);
var reader = new BsonBinaryReader(response)

while (!reader.EndOfStream)
{
    if (reader.GotEnoughData())
    {
        var bson = BsonSerializer.Deserialize<BsonDocument>(reader);
    }
}
rene
  • 41,474
  • 78
  • 114
  • 152
SOK
  • 515
  • 6
  • 21

1 Answers1

0

I solved the issue using the answer from https://stackoverflow.com/a/28036366/1435802 with a 16MB (Max BSON document size) buffer as input to the BsonBinaryReader.

For be able to read until end of stream i used the following:

public static Task WhileNotEndOfStreamAsync(this Stream stream, Action action, CancellationToken token = default(CancellationToken))
{
    return Task.Run(() => {
        try
        {
            while (!token.IsCancellationRequested)
            {
                action();
            }
        }
        catch (EndOfStreamException)
        {
            // Swallow the 'EndOfStream' Exception
        }
    }, token);
}

To read the data until EOS:

using (var response = new ReadSeekableStream(networkStream))
using (var reader = new BsonBinaryReader(response))
{
    await response.WhileNotEndOfStreamAsync(() =>
    {
        var bson = BsonSerializer.Deserialize<BsonDocument>(reader);
    }, token);
}
Community
  • 1
  • 1
SOK
  • 515
  • 6
  • 21