0

I'm trying to download a file using socket and server in java.

myClient = new Socket(address,port);
   myClient.setSoTimeout(MyFileManager.TIME_OUT);
   in = new DataInputStream(myClient.getInputStream());
   out = new DataOutputStream(myClient.getOutputStream());
File requestedFile = new File(_fileManager.getDir()+fileName); //creating the new file
 //         requestedFile.createNewFile(); //now it does
          fos = new FileOutputStream(requestedFile);
          long size = in.readLong(); //get the size
          for (int i=1; i<=size; i++) {
           try {
            fos.write(in.read());
           }
           catch (IOException e) {
            e.printStackTrace();
           }
          }

I'm sending the other side the file size and then sending each byte, right before the bytes end, it throws the above exception, saying conncetion reset.

what could be the problem?

Thank you!

2
  • Please format your code using Markdown. Commented Jun 21, 2010 at 9:06
  • I'm wondering where you found a DataInputStream.read(void) method. Commented Jun 21, 2010 at 9:35

2 Answers 2

2

Why do you think that this line returns the number of bytes in the stream??

long size = in.readLong(); //get the size

You should do in.read() until it returns -1.

Sign up to request clarification or add additional context in comments.

Comments

0

I think that the loop should be something like:

 for (int i=0; i<size; i++)...

Since streams are 0 based.

Also, you might want to keep reading until you hit the EOF rather than reading a specific number of bytes. See this tutorial to learn how :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.