BsonBinaryReader with NetworkStream

本文关键字:NetworkStream with BsonBinaryReader | 更新日期: 2023-09-27 18:16:40

是否有可能使BsonBinaryReader接受不可寻的流,例如NetworkStream?

所以我不需要持久保存所有的数据,然后通过BsonBinaryReader开始解析它,而是可以在飞行中发生?

的例子:

var response = new NetworkStream(MAGIC);
var reader = new BsonBinaryReader(response)
while (!reader.EndOfStream)
{
    if (reader.GotEnoughData())
    {
        var bson = BsonSerializer.Deserialize<BsonDocument>(reader);
    }
}

BsonBinaryReader with NetworkStream

我用一个16MB (最大BSON文档大小)缓冲区作为BsonBinaryReader的输入,使用https://stackoverflow.com/a/28036366/1435802的答案解决了这个问题。

为了能够读取到流的结尾,我使用了以下命令:

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

读取数据直到EOS:

using (var response = new ReadSeekableStream(networkStream))
using (var reader = new BsonBinaryReader(response))
{
    await response.WhileNotEndOfStreamAsync(() =>
    {
        var bson = BsonSerializer.Deserialize<BsonDocument>(reader);
    }, token);
}