I have a code that sends file to a server via server socket. My problem is that for some files the code works perfectly but for an unknown reason for some other files it loses the last chunk so the file is corrupted.
I would appreciate any help from anyone. Thank you.
The client code.
@Override
public void run(){
for (File file: sendingFiles){
try{
socket=new Socket(host, port);
out=new BufferedOutputStream(socket.getOutputStream());
fileIn=new FileInputStream(file);
byte[] buf=new byte[40*1024];
int readByte;
while((readByte=fileIn.read(buf, 0, buf.length))>0){
out.write(buf, 0, readByte);
}
System.out.println("client out of loop");
fileIn.close();
in.close();
out.close();
socket.close();
cancel=false;
}catch (IOException e){
e.printStackTrace();
this.finish();
}catch (Exception e){
e.printStackTrace();
this.finish();
}
}
this.finish();
}
server code:
@Override
public void run(){
try{
in=new BufferedInputStream(socket.getInputStream());
out=new PrintWriter(socket.getOutputStream(), true);
fileOut=new BufferedOutputStream(new FileOutputStream(receivingFile));
byte[] buf=new byte[40*1024];
out.println("continue");
int readByte=0;
while ((readByte=in.read(buf, 0, buf.length))>0){
fileOut.write(buf, 0, readByte);
}
this.finish();
}catch (IOException e){
this.finish();
}catch (Exception e){
this.finish();
}
}
and the finish method where the stream is flushed and closed
private void finish(){
if (fileOut!=null){
try{
fileOut.flush();
fileOut.close();
}catch (IOException e){}
}
if (socket!=null){
try{
socket.close();
}catch (IOException e){}
}
if (in!=null){
try{
in.close();
}catch (IOException e){}
}
if (out!=null){
out.close();
}
}
Please help me. I can t find where is the error!!!!
Solved. I just put the out flush into the loop and it worked perfectly.
Thank you very much my friends.