Thursday, 12 September 2013

How can I make sure I received whole file through socket stream?

How can I make sure I received whole file through socket stream?

Ok, So I'm making a Java program that has a server and client and I'm
sending a Zip file from server to client. I have sending the file down,
almost. But recieving I've found some inconsistency. My code isn't always
getting the full archive. I'm guessing it's terminating before the
BufferedReader has the full thing. Here's the code for the client:
public void run(String[] args) {
try {
clientSocket = new Socket("jacob-custom-pc", 4444);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedInputStream(clientSocket.getInputStream());
BufferedReader inRead = new BufferedReader(new
InputStreamReader(in));
int size = 0;
while(true) {
if(in.available() > 0) {
byte[] array = new byte[in.available()];
in.read(array);
System.out.println(array.length);
System.out.println("recieved file!");
FileOutputStream fileOut = new
FileOutputStream("out.zip");
fileOut.write(array);
fileOut.close();
break;
}
}
}
} catch(IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
So how can I be sure the full archive is there before it writes the file?

No comments:

Post a Comment