Fatih Gee
Fatih Gee

Reputation: 236

InputStream read() method never returns -1 (Java)

I am trying to send Files with JAVA. My problem is that the client never knows if the end of the file is reached or not. So the while loop of the Client never ends. Please help me.

Server (sends Data to Client)

File myFile = new File("C://LEGORacers.exe");

      byte[] mybytearray = new byte[(int) myFile.length()];
      BufferedInputStream bis = null;
      OutputStream os = null;

        bis = new BufferedInputStream(new FileInputStream(myFile));
        bis.read(mybytearray, 0, mybytearray.length);

        os = socket.getOutputStream();      
        os.write(mybytearray, 0, mybytearray.length);       
        os.flush();

        bis.close();

Client (gets Data from Server)

byte[] buf = new byte[1024];
    InputStream is = null;
    int bytesRead = 0;

    is = client.getInputStream();
    FileOutputStream fos = null;
    fos = new FileOutputStream("C://copy.exe");


    BufferedOutputStream bos = new BufferedOutputStream(fos);

     try {
            while (-1 != (bytesRead = is.read(buf, 0, buf.length))) {
            // This while loop never ends because is.read never returns -1 and I don't know why...

                bos.write(buf, 0, bytesRead);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
               is.close();
               bos.flush();
               bos.close();
               fos.close();

        }

Upvotes: 0

Views: 1754

Answers (2)

Sean
Sean

Reputation: 91

Did you close your OutputStream on your Server? If not, your loop might be perpetually setting bytesRead to 0, so you may need to close that stream.

If you need the Server's OutputStream to still be open after sending data, you could also send the size of the data in bytes at the beginning of the stream, and loop until you have all of the bytes the Server indicates it will send.

Upvotes: 1

MadConan
MadConan

Reputation: 3767

Close the socket output stream on the server. Flushing doesn't terminate the stream, which is what you need to do to send the signal that the server is done writing. From what you posted, I don't see where you close the output stream on the server side.

Upvotes: 1

Related Questions