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 解析它以进行调试。

更新:

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

4

2 回答 2

1

实现您自己的TeeStream派生类StreamMemoryStream每次读取时都会写入该类。

于 2013-08-20T12:31:00.573 回答
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 }))
…
于 2013-08-21T00:29:31.070 回答