2017-12-09 6 views
0

클라이언트 측에서 서버 측으로 파일을 보내려고합니다. 여기서 WritableGUI는 텍스트 영역에 파일 이름을 표시하는 인터페이스입니다. 파일이 서버로 전송되었지만 손상되었습니다. 때로는 전송 된 파일 크기가 맞지만 파일 크기가 0KB 인 경우도 있습니다. 내 코드가 뭐가 잘못 됐어?소켓 프로그래밍에서 파일이 손상됩니다.

클라이언트 측 :

public class FileClient { 

    private Socket s; 
    private String fileName; 
    private long fileLength; 

    public FileClient(String host, int port, String file, String fileName, long FileLength) { 
     this.fileName = fileName; 
     this.fileLength = FileLength; 
     try { 
      s = new Socket(host, port); 
      sendFile(file); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    public void sendFile(String file) throws IOException { 
     DataOutputStream dos = new DataOutputStream(s.getOutputStream()); 
     FileInputStream fis = new FileInputStream(file); 
     byte[] buffer = new byte[1024]; 
     dos.writeUTF(fileName); 
     dos.writeLong(fileLength); 
     while (fis.read(buffer) > 0) { 
      dos.write(buffer); 
     } 
     fis.close(); 
     dos.close(); 
    } 
}  

서버 측 : 평소처럼

public class FileServer extends Thread { 

    ServerSocket server; 
    int port = 8877; 
    WritableGUI gui; 

    public FileServer(WritableGUI gui, int SOCKET_PORT) throws IOException { 
     this.port = SOCKET_PORT; 
     this.gui = gui; 

     try { 
      server = new ServerSocket(port); 
     } catch (IOException ex) { 
      Logger.getLogger(MessageListener.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 

    public void run() { 
     while (true) { 
      try { 
       Socket clientSock = server.accept(); 
       saveFile(clientSock); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    private void saveFile(Socket clientSock) throws IOException { 
     DataInputStream dis = new DataInputStream(clientSock.getInputStream()); 
     FileOutputStream fos = new FileOutputStream(dis.readUTF()); 
     byte[] buffer = new byte[1024]; 

     gui.write("File Received: " + dis.readUTF()); 

     long filesize = dis.readLong(); // read file size in separate msg 
     int read = 0; 
     int totalRead = 0; 
     int remaining = (int) filesize; 
     while ((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) >= 0) { 
      totalRead += read; 
      remaining -= read; 
      System.out.println("read " + totalRead + " bytes."); 
      fos.write(buffer, 0, read); 
     } 
     dis.close(); 
     fos.close(); 
    } 
} 

답변

0
while (fis.read(buffer) > 0) { 
     dos.write(buffer); 
    } 

. 복사 루프가 잘못되었습니다. 이것을 시도하십시오 :

int count; 
while ((count = fis.read(buffer)) > 0) { 
     dos.write(buffer, 0, count); 
    } 

그리고 왜 좋은지 생각해보십시오.

+0

여전히 작동하지 않습니다. 파일이 손상됩니다. –

+0

복제본에서 내 대답보기. – EJP