1

I'm making File Transfer Thread with java

Here is Server's Code

(fileWriter = new BufferedOutputStream(fileTransferSocket.getOutputStream()))

        try {
            BufferedInputStream fileReader = new BufferedInputStream(new FileInputStream(CLIENT_PATH + "/" + filename));

            int packet;

            while((packet = fileReader.read()) != -1)
                fileWriter.write(packet);

            fileWriter.flush();
            fileReader.close();

            System.out.println(filename + " send complete");
        }

And Client's Code

(fileReader = new BufferedInputStream(fileTransferSocket.getInputStream()))

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

                int packet;

                while((packet = fileReader.read()) != -1)
                    fileWriter.write(packet);

                System.out.println(filename + " receive complete.");
                fileWriter.close();
            }

Server Prints

    System.out.println(filename + " send complete");

It means Server send every bytes of file.

However, Client doesn't print

System.out.println(filename + " receive complete.");

I checked how many times while loop runs(Checked Both, server and client)

Both while loops runs 685 times

I think Client's while loop doesn't recognize end of file transfer.

Anyone knows problem?

Jonno_FTW
  • 8,601
  • 7
  • 58
  • 90
Kanghoi Choi
  • 69
  • 11

2 Answers2

1

To send EOF to the socket, close fileWriter at the server.

while((packet = fileReader.read()) != -1)
   fileWriter.write(packet);

fileWriter.close(); // note
fileReader.close();
Radiodef
  • 37,180
  • 14
  • 90
  • 125
-1

You can test print -1 in your service to tell the end of the transform :

while((packet = fileReader.read()) != -1)
            fileWriter.write(packet);
fileWriter.write(-1);
Feng Lin
  • 670
  • 4
  • 8
  • It doens't work either... I cannot escape while loop. – Kanghoi Choi Oct 28 '14 at 01:40
  • 1
    This is not right. Sending -1 just sends the byte value `0xFF`. -1 is returned specially by an input stream `read` method, it is not part of the stream itself. – Radiodef Oct 28 '14 at 01:55
  • It seems that in basic input or output stream the byte is from 0-255 ,so in data transform level you can not tell the client that is end.Otherwise you close the socket or use the application logic data replace the end , not only the -1 in client.It may be some special characters. – Feng Lin Oct 28 '14 at 02:01