在以字节为单位读取大量数据时,while循环将在最后几个字节中跳闸

时间:2014-06-09 05:27:40

标签: c# tcplistener

我发送8254789字节的字节。它正在经历循环但是当它到达8246597并且必须读取8192个字节。它从while循环到无处。有人可以解释一下,问题是什么?

 public static byte[] ReadFully(Stream stream, int initialLength)
{
    // If we've been passed an unhelpful initial length, justS
    // use 32K.
    if (initialLength < 1)
    {
        initialLength = 32768;
    }

    byte[] buffer = new byte[3824726];
    int read = 0;
    int chunk;
    try
    {

        while ((chunk = stream.Read(buffer, read, 3824726 - read)) > 0)
        {
            Console.WriteLine("Length of chunk" + chunk);
            read += chunk;
            Console.WriteLine("Length of read" + read);
            if (read == 0)
            {
                stream.Close();
                return buffer;
            }
            // If we've reached the end of our buffer, check to see if there's
            // any more information
            if (read == buffer.Length)
            {
                Console.WriteLine("Length of Buffer" + buffer.Length);
                int nextByte = stream.ReadByte();

                // End of stream? If so, we're done
                if (nextByte == -1)
                {
                    return buffer;
                }

                // Nope. Resize the buffer, put in the byte we've just
                // read, and continue
                byte[] newBuffer = new byte[buffer.Length * 2];
                Console.WriteLine("Length of newBuffer" + newBuffer.Length);
                Array.Copy(buffer, newBuffer, buffer.Length);
                newBuffer[read] = (byte)nextByte;
                buffer = newBuffer;
                read++;                        
            }
        }

        // Buffer is now too big. Shrink it.
        byte[] ret = new byte[read];
        Array.Copy(buffer, ret, read);
        return ret;
    }
    catch (Exception ex)
    { throw ex; }
}      

1 个答案:

答案 0 :(得分:0)

通常你不会像那样写你的流循环。而是尝试这样的事情:

byte[] buffer = new byte[BUFFER_SIZE];
int read = -1;
while((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
    // ... use read bytes in buffer here
}

你每次都试图调整你的偏移量,但你不需要因为使用游标 - 所以你基本上是在跳过。