Exemplo n.º 1
0
        /// <summary>
        /// Read targetLength bytes into target from buffered connection.
        /// </summary>
        public void Read(byte[] target, int targetLength)
        {
            int targetOffset = 0;

            do
            {
                // Read from buffer.
                if (this.pos < this.len)
                {
                    int size = this.len - this.pos;

                    if (targetLength <= size)
                    {
                        // Buffer contains enough bytes.  Copy buffer to target and return.
                        Buffer.BlockCopy(this.buffer, this.pos, target, targetOffset, targetLength);
                        this.pos += targetLength;
                        return;
                    }

                    // Buffer contains partial bytes.  Copy remaining buffer to target
                    // and fall through to socket read to receive more bytes.
                    Buffer.BlockCopy(this.buffer, this.pos, target, targetOffset, size);
                    targetLength -= size;
                    targetOffset += size;
                }

                // Read from socket. Try to fill entire buffer.
                this.len = conn.Read(this.buffer, 0, this.buffer.Length);

                if (this.len <= 0)
                {
                    throw new SocketException((int)SocketError.ConnectionReset);
                }

                this.pos = 0;
            } while (true);
        }