2011-11-20 2 views
1

Java 소켓으로 놀고 있었는데 서버에서 클라이언트로 파일을 전송하려했지만 전송이 손상되었습니다. 파일이 완전히 전송하지만 제대로 도착파일을 전송할 때 자바 소켓으로 손상되었습니다.

public void downloadFile(String fileName) { 
    try { 
     this.client= new Socket(ip,port); 
     DataInputStream input= new DataInputStream(this.client.getInputStream()); 
     DataOutputStream ouput= new DataOutputStream(this.client.getOutputStream()); 

     output.writeUTF("DOWNLOAD"); 
     output.writeUTF(fileName); 

     File f = new File(path+ fileName); 
     file = new FileOutputStream(f); 
     byte[] buffer = new byte[1024]; 
     int len; 
     while ((len = input.read(buffer)) > 0) { 
      file.write(buffer, 0, len); 
     } 
     file.flush(); 
     file.close(); 
     this.client.close(); 
    } catch (Exception e) { 
     System.out.println("something went wrong"); 
    } 
} 

내가 뭘 잘못 몰라 : 클라이언트 측에서

DataInputStream input; 
DataOutputStream ouput; 
//these two variable are initialized somewhere else in the code. 
private void downloadFile() { 
    try { 
     String fileName= input.readUTF(); 
     File f = new File(path + fileName); 
     size= f.length(); 
     file= new FileInputStream(path+ fileName); 
     ouput.writeLong(size); 
     byte[] buffer = new byte[1024]; 
     int len; 
     while ((len = file.read(buffer)) > 0) { 
      output.write(buffer, 0, len); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

:이 서버에서 코드입니다. 서버

답변

3

: 그것은 이진 데이터의 한 부분 인 것처럼

클라이언트 측에서이를 처리하는 것 해달라고
ouput.writeLong(size); 

, 당신은 단지 그것을 다운로드 한 파일에 추가합니다. 당신은 서버에서 클라이언트로 파일의 길이를 보내처럼

1

같습니다 :

ouput.writeLong(size); 

하지만이의 처음 몇 바이트를 차지하므로 클라이언트 코드는 결코 전송 크기가 아무것도하지 않습니다 파일.

관련 문제