0

On receiving Multipart data from the browser (which has a size of greater than ~2KB), I start receiving null '\0' bytes after the first few chunks which are relevant when I use:

_Stream.Read(ByteArray, Offset, ContentLength);

But, if I divide the ContentLength into small buffers (around 2KB each) AND add a delay of 1ms after each call to Read(), then it works fine:

for(int i = 0; i < x; i++)
{
    _Stream.Read(ByteArray, Offset * i, BufferSize);
    System.Threading.Thread.Sleep(1);
}

But, adding delay is quite slow. How to prevent reading null bytes. How can I know how many bytes have been written by the browser.

Thanks

0

1 Answer 1

2

The 0x00 bytes were not actually received, they were never written to.

Stream.Read() returns the number of bytes actually read, which is in your case often less than BufferSize. Small amounts of data typically arrive in a single message, in which case the problem does not occur.

The delay might "work" in your test scenario because by then the network layer has buffered more than BufferSize data. It will probably fail in a production environment.

So you'll need to change your code into something like:

int remaining = ContentLength;
int offset = 0;  
while (remaining > 0)
{
    int bytes = _Stream.Read(ByteArray, offset, remaining);
    if (bytes == 0)
    {
        throw new ApplicationException("Server disconnected before the expected amount of data was received");
    }

    offset += bytes;
    remaining -= bytes;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.