从同一SslStream同时读取? [英] Reading from same SslStream simultaneously?
问题描述
我目前从SslStream读取XML数据。流是从的TcpClient对象来了。
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:
...
此外,我想读取来自TcpClient的每一个比特和字节直接不管是XML数据或没有。我怎样才能读取相同数据流的两倍?是否有可能用XmlReader的和阅读的不知何故倾流的内容?
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?
我想看到什么是从流到来,它是如何通过的XmlReader解析进行调试。
I would like to see what is coming from the stream and how it is parsed via XmlReader for debugging.
更新:
我想保持一个流运行而不是有两个独立的数据流。因为我已经有数据它没有意义在我的应用程序在内存中再次拥有它。
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.
推荐答案
如果对刚读出的数据的回调是正常的,你可以创建一个包装流
这正是这么做的:
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
}
用法是这样的:
var teeStream = new TeeStream(sslStream, (bytes, read) => /* whatever */);
using (XmlReader reader = XmlReader.Create(
teeStream, new XmlReaderSettings { Async = true }))
…
这篇关于从同一SslStream同时读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!