我当前正在从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对其进行解析以进行调试。
更新:
我想保持一个流运行,而不是有两个独立的流。由于我已经有了数据,所以在我的应用程序中,将数据再次存储在内存中是没有意义的。
如果刚刚读取的数据的回调对您来说是可以的,那么您可以创建一个包装器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 }))
…
实现您自己的TeeStream
类,该类派生自Stream
,每次读取时都会写入一个MemoryStream
。