Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a stream into a file doesn't work propely

I am making a program that transports a file in chunks over TCP. Now, Each time I transfer a file a little bit at the end doesn't seem to be written in and so if I try to transfer a picture at the bottom right there are glitches. Now, my first idea was that when I read, transfer and write the final chunk that is smaller that the buffer length, I write in a lot of zeroes too. So I tried to change the last buffer size accordingly. I then tried that out using a small text file that only has HELLO WORLD written in it, but when I write it in, and then open the file, it is empty.

Here is the reading and sending code where range[0] is the first part and range[1 ] is the last part:

byte[] buffer = new byte[DATA_BUFF_SIZE];
using (Stream input = File.OpenRead(file.Path))
{
    Console.WriteLine("SENT PARTS # ");
    for (int i = range[0]; i <= range[1]; i++)
    {
        Console.Write("PART " + i + ", ");

        if (i == range[1])
        {
            buffer = new byte[input.Length - input.Position];
        }

        input.Position = i * DATA_BUFF_SIZE;
        input.Read(buffer, 0, buffer.Length);

        netStream.Write(buffer, 0, buffer.Length);

    }
    Console.WriteLine("LENGTH = " + input.Length);
}

here is the receiving and writing code:

int bytesReceived = 0;
int index = partRange.First;
int partNum = 0;
byte[] receiveBuffer = new byte[BUFF_SIZE];

if (index == partRange.Last)
{
    receiveBuffer = new byte[fileToDownload.Length - index * BUFF_SIZE];
}

while ((bytesReceived = netStream.Read(receiveBuffer, 0, receiveBuffer.Length)) > 0)
{
    Console.Write("INDEX:" + index + ", ");
    output.Position = index * BUFF_SIZE;
    output.Write(receiveBuffer, 0, receiveBuffer.Length);
    index++;
    partNum++;

    if (partNum > (partRange.Last - partRange.First))
    {
        break;
    }

    if (index == partRange.Last)
    {
        receiveBuffer = new byte[fileToDownload.Length - index * BUFF_SIZE];
    }
}
Console.WriteLine();

What am I missing? I even printed out the buffer on client and server and it is equal.

Any help would be appreciated, thanks.

like image 599
Foxman Avatar asked Oct 30 '22 12:10

Foxman


1 Answers

Try netStream.Flush();

I suspect what's happening is the stream is getting closed before the writing finishes. Sometimes the output stream will continue to write asynchronously. You'll find this when dealing with file streams too. Using Flush() forces the stream to finish whatever writing operation it is doing before continuing execution.

like image 68
A.Konzel Avatar answered Nov 15 '22 04:11

A.Konzel