问题
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