質問

現在、というものはありません NetworkStream.Peek 方法クライアントまで、フルのC#.何が最良の方法の実施などの方法るように NetworkStream.ReadByte ことを除いて、返される byte ていないから削除 Stream?

役に立ちましたか?

解決

必要がない場合に実際に取得するにバイトを参照することができ DataAvailable 物件です。

それ以外の場合は、できなどで包んで、 StreamReader およびコード Peek 方法。

注意するもので、特に信頼性から読み込みを行うためのネットワークストリームにより、遅延の課題です。のデータが利用可能(現在のバッファ)の瞬間 まpeek.

お使いいただくことによってもいいことが、 Read 方法 NetworkStream はブロックに電話は、不要なのかもしれませんのチェック状態の場合でも、受けているチャンク.だという意見はあ応応答を読みながらストリームからのものを使用できるスレッドは非同期通話データを受信するためです。

編集:による このポスト, StreamReader.Peek はバギーに NetworkStream, 時間は非正規滞在行動するように注意してくださいだった。


更新への対応のコメント

の概念を"覗"の実際のストリーム自体が実際にことができないようなだから、ストリームのバイトを受信しなくなったら、ストリームです。一流の支援を求めるのですが技術的に再読み込みそのバイトが NetworkStream なります。

覗くだけの場合に適用されているストリームを読み込むバッファ;このデータはバッファーを覗いてみたらすのですぐチェックインなので、現在位置のバッファです。その StreamReader できること;no Stream クラスは一般に独自の Peek 方法。

現在、この問題を具体的には、疑問に思ったのかどうかこんで、右の答えです。私の考えを動的に選択方法の処理、ストリームだけ 本当に 必要なのはこの原ストリーム?きを読まないストリームへバイト配列の最初、ともにコピーする MemoryStream, で処理し、そのときから。

主な発見であれば悪い場合のだから読み込むネットワークストリームにデータがなくなっています。だ読んで一時的なロケーション、デバッグです。また、このサイトでのデータは、そのオブジェクトのためのデータ処理に失敗した中途半端。

一般に、初めてのことだいたいと NetworkStream 読み出し現地のバッファです。理由はただそれだけして私が考えられることはいわない"ということばを読み込む大量のデータ、それでも性を高めることが考えられますが、そのファイルを用いてシステムとして中間バッファばんわ。

わからないお厳しい要求がいかにアドバイスすることはできない。なおデータから直接 NetworkStream がある場合を除き、やむを得ない理由です。検討の読み込みデータをメモリにロードすることにより又はディスク、その処理をコピーします。

他のヒント

私は「マジックナンバーのためにのぞくと、その後にストリームを送信するためにどのストリームプロセッサを決める」は同じに走った要件と、残念ながら、その問題のうち、自分の道をイタチすることはできません - Aaronaughtの答えにコメントで示唆したように - 渡すことで、すでにこれらのメソッドは、与えられたとして、別のパラメータのストリーム処理方法にバイトを消費し、彼らはSystem.IO.Streamと他には何を期待しています。

私は、ストリームをラップ多かれ少なかれ普遍の PeekableStream のクラスを作成し、これを解決しました。それはNetworkStreamsのために動作しますが、また、他のストリームのために、のStream.CanRead のそれをあなたに提供します。

<時間>

編集

また、あなたはブランドの新しい ReadSeekableStreamするそして、やる

var readSeekableStream = new ReadSeekableStream(networkStream, /* >= */ count);
...
readSeekableStream.Read(..., count);
readSeekableStream.Seek(-count, SeekOrigin.Current);
<時間> いずれにせよ、ここに来てPeekableStreamます:

/// <summary>
/// PeekableStream wraps a Stream and can be used to peek ahead in the underlying stream,
/// without consuming the bytes. In other words, doing Peek() will allow you to look ahead in the stream,
/// but it won't affect the result of subsequent Read() calls.
/// 
/// This is sometimes necessary, e.g. for peeking at the magic number of a stream of bytes and decide which
/// stream processor to hand over the stream.
/// </summary>
public class PeekableStream : Stream
{
    private readonly Stream underlyingStream;
    private readonly byte[] lookAheadBuffer;

    private int lookAheadIndex;

    public PeekableStream(Stream underlyingStream, int maxPeekBytes)
    {
        this.underlyingStream = underlyingStream;
        lookAheadBuffer = new byte[maxPeekBytes];
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
            underlyingStream.Dispose();

        base.Dispose(disposing);
    }

    /// <summary>
    /// Peeks at a maximum of count bytes, or less if the stream ends before that number of bytes can be read.
    /// 
    /// Calls to this method do not influence subsequent calls to Read() and Peek().
    /// 
    /// Please note that this method will always peek count bytes unless the end of the stream is reached before that - in contrast to the Read()
    /// method, which might read less than count bytes, even though the end of the stream has not been reached.
    /// </summary>
    /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and
    /// (offset + number-of-peeked-bytes - 1) replaced by the bytes peeked from the current source.</param>
    /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data peeked from the current stream.</param>
    /// <param name="count">The maximum number of bytes to be peeked from the current stream.</param>
    /// <returns>The total number of bytes peeked into the buffer. If it is less than the number of bytes requested then the end of the stream has been reached.</returns>
    public virtual int Peek(byte[] buffer, int offset, int count)
    {
        if (count > lookAheadBuffer.Length)
            throw new ArgumentOutOfRangeException("count", "must be smaller than peekable size, which is " + lookAheadBuffer.Length);

        while (lookAheadIndex < count)
        {
            int bytesRead = underlyingStream.Read(lookAheadBuffer, lookAheadIndex, count - lookAheadIndex);

            if (bytesRead == 0) // end of stream reached
                break;

            lookAheadIndex += bytesRead;
        }

        int peeked = Math.Min(count, lookAheadIndex);
        Array.Copy(lookAheadBuffer, 0, buffer, offset, peeked);
        return peeked;
    }

    public override bool CanRead { get { return true; } }

    public override long Position
    {
        get
        {
            return underlyingStream.Position - lookAheadIndex;
        }
        set
        {
            underlyingStream.Position = value;
            lookAheadIndex = 0; // this needs to be done AFTER the call to underlyingStream.Position, as that might throw NotSupportedException, 
                                // in which case we don't want to change the lookAhead status
        }
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        int bytesTakenFromLookAheadBuffer = 0;
        if (count > 0 && lookAheadIndex > 0)
        {
            bytesTakenFromLookAheadBuffer = Math.Min(count, lookAheadIndex);
            Array.Copy(lookAheadBuffer, 0, buffer, offset, bytesTakenFromLookAheadBuffer);
            count -= bytesTakenFromLookAheadBuffer;
            offset += bytesTakenFromLookAheadBuffer;
            lookAheadIndex -= bytesTakenFromLookAheadBuffer;
            if (lookAheadIndex > 0) // move remaining bytes in lookAheadBuffer to front
                // copying into same array should be fine, according to http://msdn.microsoft.com/en-us/library/z50k9bft(v=VS.90).aspx :
                // "If sourceArray and destinationArray overlap, this method behaves as if the original values of sourceArray were preserved
                // in a temporary location before destinationArray is overwritten."
                Array.Copy(lookAheadBuffer, lookAheadBuffer.Length - bytesTakenFromLookAheadBuffer + 1, lookAheadBuffer, 0, lookAheadIndex);
        }

        return count > 0
            ? bytesTakenFromLookAheadBuffer + underlyingStream.Read(buffer, offset, count)
            : bytesTakenFromLookAheadBuffer;
    }

    public override int ReadByte()
    {
        if (lookAheadIndex > 0)
        {
            lookAheadIndex--;
            byte firstByte = lookAheadBuffer[0];
            if (lookAheadIndex > 0) // move remaining bytes in lookAheadBuffer to front
                Array.Copy(lookAheadBuffer, 1, lookAheadBuffer, 0, lookAheadIndex);
            return firstByte;
        }
        else
        {
            return underlyingStream.ReadByte();
        }
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        long ret = underlyingStream.Seek(offset, origin);
        lookAheadIndex = 0; // this needs to be done AFTER the call to underlyingStream.Seek(), as that might throw NotSupportedException,
                            // in which case we don't want to change the lookAhead status
        return ret;
    }

    // from here on, only simple delegations to underlyingStream

    public override bool CanSeek { get { return underlyingStream.CanSeek; } }
    public override bool CanWrite { get { return underlyingStream.CanWrite; } }
    public override bool CanTimeout { get { return underlyingStream.CanTimeout; } }
    public override int ReadTimeout { get { return underlyingStream.ReadTimeout; } set { underlyingStream.ReadTimeout = value; } }
    public override int WriteTimeout { get { return underlyingStream.WriteTimeout; } set { underlyingStream.WriteTimeout = value; } }
    public override void Flush() { underlyingStream.Flush(); }
    public override long Length { get { return underlyingStream.Length; } }
    public override void SetLength(long value) { underlyingStream.SetLength(value); }
    public override void Write(byte[] buffer, int offset, int count) { underlyingStream.Write(buffer, offset, count); }
    public override void WriteByte(byte value) { underlyingStream.WriteByte(value); }
}
ここであなただけの(任意の時点で覗き見することができることではなく)ストリームの開始時に特定のバイト数を覗き見することができます非常に単純なPeekStreamの実装です。覗くバイトは、既存のコードに対する変更を最小限に抑えるために、Stream自体として返されます。

ここであなたがそれを使用する方法は次のとおりです。

Stream nonSeekableStream = ...;
PeekStream peekStream = new PeekStream(nonSeekableStream, 30); // Peek max 30 bytes
Stream initialBytesStream = peekStream.GetInitialBytesStream();
ParseHeaders(initialBytesStream);  // Work on initial bytes of nonSeekableStream
peekStream.Read(...) // Read normally, the read will start from the beginning

GetInitialBytesStream()(ストリームがpeekSizeより短い場合以下)基本となるストリームの最初のバイトをpeekSizeまで含まシークストリームを返します。

理由は、そのシンプルさの

は、PeekStreamを読むことだけで、直接基礎となるストリームを読み込むよりも遅い(もし全てで)わずかにする必要があります。

public class PeekStream : Stream
{
    private Stream m_stream;
    private byte[] m_buffer;
    private int m_start;
    private int m_end;

    public PeekStream(Stream stream, int peekSize)
    {
        if (stream == null)
        {
            throw new ArgumentNullException("stream");
        }
        if (!stream.CanRead)
        {
            throw new ArgumentException("Stream is not readable.");
        }
        if (peekSize < 0)
        {
            throw new ArgumentOutOfRangeException("peekSize");
        }
        m_stream = stream;
        m_buffer = new byte[peekSize];
        m_end = stream.Read(m_buffer, 0, peekSize);
    }

    public override bool CanRead
    {
        get
        {
            return true;
        }
    }

    public override bool CanWrite
    {
        get
        {
            return false;
        }
    }

    public override bool CanSeek
    {
        get
        {
            return false;
        }
    }

    public override long Length
    {
        get
        {
            throw new NotSupportedException();
        }
    }

    public override long Position
    {
        get
        {
            throw new NotSupportedException();
        }
        set
        {
            throw new NotSupportedException();
        }
    }

    public MemoryStream GetInitialBytesStream()
    {
        return new MemoryStream(m_buffer, 0, m_end, false);
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        throw new NotSupportedException();
    }

    public override void SetLength(long value)
    {
        throw new NotSupportedException();
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        // Validate arguments
        if (buffer == null)
        {
            throw new ArgumentNullException("buffer");
        }
        if (offset < 0)
        {
            throw new ArgumentOutOfRangeException("offset");
        }
        if (offset + count > buffer.Length)
        {
            throw new ArgumentOutOfRangeException("count");
        }

        int totalRead = 0;

        // Read from buffer
        if (m_start < m_end)
        {
            int toRead = Math.Min(m_end - m_start, count);
            Array.Copy(m_buffer, m_start, buffer, offset, toRead);
            m_start += toRead;
            offset += toRead;
            count -= toRead;
            totalRead += toRead;
        }

        // Read from stream
        if (count > 0)
        {
            totalRead += m_stream.Read(buffer, offset, count);
        }

        // Return total bytes read
        return totalRead;
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        throw new NotImplementedException();
    }

    public override int ReadByte()
    {
        if (m_start < m_end)
        {
            return m_buffer[m_start++];
        }
        else
        {
            return m_stream.ReadByte();
        }
    }

    public override void Flush()
    {
        m_stream.Flush();
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            m_stream.Dispose();
        }
        base.Dispose(disposing);
    }
}

免責事項:PeekStreamはとてもバグが含まれていてもよい、上記の作業プログラムから取られているが、それは総合テストしていません。それは私のために動作しますが、あなたは失敗しているいくつかのコーナーケースを発見することがあります。

scroll top