0

I'm using sockets for file transfer in java. Here is the Client code

for(int i = 0;i < fileList.size();i++) {
    String filename = (String)fileList.get(i);
    RequestFile(filename);

    try {
        BufferedOutputStream fileWriter = new BufferedOutputStream(
                                              new FileOutputStream(
                                                  new File(PROGRAM_PATH + "/" + 
                                                           filename)));         
        int packet;
        int count = 0;

        while((packet = fileReader.read()) != -1) {
            fileWriter.write(packet);
            count++;
        }

        System.out.println(filename + " receiver complete. (count : " + count + ")");
        fileWriter.flush();
        fileWriter.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

And here is the Server code

public void SendFile(String filename) {
    try {
        fileReader = new BufferedInputStream(new FileInputStream(CLIENT_PATH + "/" + filename));

        int packet;
        int count = 0;
        while((packet = fileReader.read()) != -1) {
            count++;
            fileWriter.write(packet);
        }
        fileWriter.write(-1);
        System.out.println(count);

        fileReader.close();
    }
    catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

When I checked the server's count, it was 635. It means the server had sent data 635 times. However, the client's print count is only 512. (from 0 to 511) I think it's stopped at read(), because

System.out.println(filename + " receiver complete. (count : " + count + ")");

is not printed. Can someone tell me the reason and solution?

İsmet Alkan
  • 5,361
  • 3
  • 41
  • 64
Kanghoi Choi
  • 69
  • 11
  • I think you should use `packet` to increment `count` and check whether all the bytes are getting transferred or not. – Tirath Oct 27 '14 at 12:10

1 Answers1

0

At the server side you can't send a byte with value -1 to the client. This line:

fileWriter.write(-1);

It does not do what you want. The write() method will take the lowest 8 bits of the parameter and send that as one byte (which in this case will be 0xff). At the client side fileReader.read() will receive this as 0xff (of type int) and not as -1 (of type int).

-1 is a special value indicating that end of stream has been reached. It is not a valid data to be written or read. If you send -1, the client will read that as 0xff=255. The values that can be sent and received is 0..255 both inclusive. Again, -1 is a special value for end-of-stream.

At the server side you don't flush or close the output stream. That might explain the difference (data hold in the buffer might not get through to the client).

icza
  • 389,944
  • 63
  • 907
  • 827