Reading from same SslStream simultaneously?

江枫思渺然 提交于 2019-12-08 12:22:59

问题


I am currently reading XML data from a SslStream. The stream is coming from a TcpClient object.

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:
...

Additionally I would like to read every single bit and byte from the TcpClient directly regardless whether it is XML data or not. How can I read the same stream twice? Is it possible to read it with the XmlReader and dump the stream content somehow?

I would like to see what is coming from the stream and how it is parsed via XmlReader for debugging.

UPDATE:

I would like to keep one stream running rather then having two independent streams. Since I already have the data it does not make sense in my application to have it again in the memory.


回答1:


If a callback for the data that was just read is okay for you, you could create a wrapper Stream that does exactly that:

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
}

Usage would be something like this:

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

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



回答2:


Implement your own TeeStream class derived from Stream which has a MemoryStream it writes to every time it does a read.



来源:https://stackoverflow.com/questions/18329264/reading-from-same-sslstream-simultaneously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!