Ziv Sion
Ziv Sion

Reputation: 454

Java while loop stack - blocked

I'm trying to receive a file in byte[], and I'm using:

byte[] buffer = new byte[16384]; // How many bytes to read each run

InputStream in = socket.getInputStream(); // Get the data (bytes)

while((count = in.read(buffer)) > 0) { // While there is more data, keep running
    fos.write(buffer); // Write the data to the file

    times++; // Get the amount of times the loop ran
    System.out.println("Times: " + times);
}

System.out.println("Loop ended");

The loop stops after 1293 times and then stops printing the times. But the code did not move to System.out.println("Loop ended"); - it seems like the loop is waiting for something...

Why the loop doesn't break?

Upvotes: 1

Views: 87

Answers (1)

user16632363
user16632363

Reputation: 1100

Your loop terminates only at the end of the input stream. Has the sender terminated the stream (closed the socket)? If not, then there is no end yet.

In such a case, read() will pend until there is at least one byte.

If the socket cannot be closed at the end of the file, for some reason, then you will need to find another way for the recipient to know when to exit the loop. A usual method is to first send the number of bytes that will be sent.


Your write-to-file is faulty as well, since it will attempt to write the entire buffer. But the read can return a partial buffer; that's why it returns a count. The returned count needs to be used in the write to the output file.

Upvotes: 1

Related Questions