同时从同一个SslStream中读取?

时间:2013-08-20 07:27:46

标签: c# stream async-await tcpclient c#-5.0

我目前正在从SslStream中读取XML数据。该流来自TcpClient对象。

using (XmlReader r = XmlReader.Create(sslStream, new XmlReaderSettings() { Async = true }))                
{
    while (await r.ReadAsync())
    {
        ResetStream = false;
        switch (r.NodeType)
        {
            case XmlNodeType.XmlDeclaration:
                ...
                break;
            case XmlNodeType.Element:
...

此外,我想直接从TcpClient读取每个位和字节,无论它是否是XML数据。如何两次读取相同的流?是否可以使用XmlReader 以某种方式转储流内容来读取它?

我想看看来自流的内容以及如何通过XmlReader解析它以进行调试。

更新

我想保持一个流运行,而不是有两个独立的流。由于我已经拥有了数据,因此在我的应用程序中将其重新存储在内存中是没有意义的。

2 个答案:

答案 0 :(得分:1)

实现自己的TeeStream类派生自Stream,每次执行读取时都会写入MemoryStream

答案 1 :(得分:1)

如果刚刚读取的数据的回调对你来说没问题,你可以创建一个完全相同的包装器Stream

public class TeeStream : Stream
{
    private readonly Stream m_underlyingStream;
    private readonly Action<byte[], int> m_readCallback;

    public TeeStream(Stream underlyingStream, Action<byte[], int> readCallback)
    {
        m_underlyingStream = underlyingStream;
        m_readCallback = readCallback;
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        var read = m_underlyingStream.Read(buffer, offset, count);

        m_readCallback(buffer, read);

        return read;
    }

    public override async Task<int> ReadAsync(
        byte[] buffer, int offset, int count,
        CancellationToken cancellationToken)
    {
        var read = await m_underlyingStream.ReadAsync(
            buffer, offset, count, cancellationToken);

        m_readCallback(buffer, read);

        return read;
    }

    // the remaining members that have to be overridden
    // just call the same member of underlyingStream
}

用法是这样的:

var teeStream = new TeeStream(sslStream, (bytes, read) => /* whatever */);

using (XmlReader reader = XmlReader.Create(
    teeStream, new XmlReaderSettings { Async = true }))
…