SOK SOK - 23 days ago 9
C# Question

BsonBinaryReader with NetworkStream

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);
}
}

SOK SOK
Answer

I solved the issue using the answer from http://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);
}
Comments