2014-04-24 7 views
2

좋아요. 그래서 소켓을 통해 여러 파일을 전송해야하는 코드 블록이 있습니다. 내가 이것을 for 루프에서 수행하는 방법은 소켓을 여는 것입니다 -> 파일 전송 -> 소켓을 닫고 다른 파일을 반복하십시오. 상기 코드 아래에 :소켓을 통해 전송하는 동안 무작위 오류가 발생했습니다.

for (int i = 0; i < fname.size(); i++) { 
      Socket sok = new Socket("localhost",4444); 
      PrintStream oos = new PrintStream(sok.getOutputStream()); 
      oos.println("1"); 
      try { 

       System.out.println(fname.get(i)); 
       File myFile = new File(path+fname.get(i)); 
       byte[] mybytearray = new byte[(int) myFile.length()]; 

       FileInputStream fis = new FileInputStream(myFile); 
       BufferedInputStream bis = new BufferedInputStream(fis); 
       // bis.read(mybytearray, 0, mybytearray.length); 

       DataInputStream dis = new DataInputStream(bis); 
       dis.readFully(mybytearray, 0, mybytearray.length); 

       OutputStream os = sok.getOutputStream(); 

       // Sending file name and file size to the server 
       DataOutputStream doss = new DataOutputStream(os); 
       doss.writeUTF(myFile.getName()); 
       doss.writeLong(mybytearray.length); 
       doss.write(mybytearray, 0, mybytearray.length); 
       doss.flush(); 
       sok.close(); 
       System.out.println("File " + fname.get(i) + " sent to Server."); 

      } catch (Exception e) { 
       System.err.println("File does not exist! (May not be true) Generated Error: "+e); 
      } 


      //sendFile(path+fname.get(i)); 
      //sock.close(); 
     } 
    } catch (Exception e) { 
     System.err.println(e); 
    } 

이제 어떻게 발생하면, 오류를 뱉어 사실 중요하지 않습니다 클라이언트입니다, 그것은 실제로 파일이 서버에 송신 말한다. 이제 서버가 임의의 오류를 발생시킵니다. 때로는 서버가 일부 파일 (모든 파일을 수신하지 못하는 경우도 있음)과 파일을 수신하지 못하는 경우가 있으며, 나오는 오류는 임의적입니다. 오류는 다음 중 하나 또는 조합입니다.

java.io.EOFException 
java.io.FileNotFoundException 
java.net.SocketException: Connection reset 
java.io.UTFDataFormatException 

이러한 오류는 전송하는 동안 서버쪽에 있습니다.

public void receiveFile() { 


    try { 
     int bytesRead; 

     DataInputStream clientData = new DataInputStream(
       clientSocket.getInputStream()); 

     String fileName = clientData.readUTF(); 
     OutputStream output = new FileOutputStream((fileName)); 
     long size = clientData.readLong(); 
     byte[] buffer = new byte[100000]; 
     while (size > 0 
       && (bytesRead = clientData.read(buffer, 0, 
         (int) Math.min(buffer.length, size))) != -1) { 
      output.write(buffer, 0, bytesRead); 
      size -= bytesRead; 
     } 

     output.close(); 
     clientData.close(); 

     System.out.println("File " + fileName + " received from client."); 
    } catch (IOException ex) { 
     System.err.println("Client error. Connection closed.  " +ex); 
    } 
} 

스택 트레이스 : : 여기에 무슨 일 =/

서버 코드 모르겠습니다으로 클라이언트에서 명령을 수신 코드를 요청

java.io.EOFException 
    at java.io.DataInputStream.readUnsignedShort(Unknown Source) 
    at java.io.DataInputStream.readUTF(Unknown Source) 
    at java.io.DataInputStream.readUTF(Unknown Source) 
    at ClientConnection.receiveFile(ClientConnection.java:80) 
    at ClientConnection.run(ClientConnection.java:46) 
    at java.lang.Thread.run(Unknown Source) 

1 
Accepted connection : Socket[addr=/127.0.0.1,port=60653,localport=4444] 
File LF-statistikkboka(Myers).pdf received from client. 
1 
java.io.EOFException 
    at java.io.DataInputStream.readUnsignedShort(Unknown Source) 
    at java.io.DataInputStream.readUTF(Unknown Source) 
    at java.io.DataInputStream.readUTF(Unknown Source) 
    at ClientConnection.receiveFile(ClientConnection.java:80) 
    at ClientConnection.run(ClientConnection.java:46) 
    at java.lang.Thread.run(Unknown Source) 

File WHAT IS LEFT TO DO.docx received from client. 

in = new BufferedReader(new InputStreamReader(
       clientSocket.getInputStream())); 
     String clientSelection; 
     clientSelection = in.readLine(); 
     System.out.println(clientSelection); 
     while ((clientSelection) != null) { 
      switch (clientSelection) { 
      case "1": 
       receiveFile(); 
       break; 
      case "2": 
       String outGoingFileName; 
       while ((outGoingFileName = in.readLine()) != null) { 
        sendFile(outGoingFileName); 
       } 
       break; 
      case "3": 
       sync(); 
       break; 
      default: 
       System.out.println("Incorrect command received."); 
       break; 
      } 
      //in.close(); 
      break; 
     } 
+0

오류가 발생한 서버 코드를 표시하십시오. 맞습니까? –

+0

완료. 파일을 수신하고 오류를 내뿜는 함수입니다. –

+0

그리고 어떤 전화가 예외를 던지고 있습니까? (스택 트레이스는 무엇입니까?) –

답변

0

범인은 아마도 클라이언트 코드에서 몇 줄 일 것입니다 :

문자열 "1"은 연결을 통해 전송되지만 수신 할 서버 코드가 없으므로 파일 이름과 혼동되어 파일 이름이 파일 데이터로 해석되고 파일 데이터는 너무 짧아서 많은 예외가 있습니다. 값이 상수이기 때문에 문자열 "1"을 전송할 필요가없는 것처럼 보이므로 해당 행을 제거하면 적어도 부분적으로 수정해야합니다.

+0

그 부분이 작동합니다. 코드의 다른 부분에 있습니다. 그 이유는 명령을 사용하여 파일을 수신 할 서버를 준비 할 수 있기 때문입니다. –

+0

"1"을받는 코드를보고 싶습니다. 문제가있을 수 있습니다. – tbodt

0

다음 데이터 중 일부를 '훔칠'BufferedReader로 '1'행을 읽어야합니다. DataInputStream.readUTF()를 사용하면 (자), 다음의 파일을 읽어 내기 위해서 (때문에) 사용하는 것과 같은 DataInputStream를 사용해 스트림으로부터 커멘드를 읽어 들이지 않으면 안됩니다. DataOutputStream.writeUTF()를 사용해, 그 DataInputStream를 송신 해 사용하는 것과 같은 DataOutputStream를 사용해 커멘드를 기입 할 필요가 있습니다. 파일.

NB 전체 파일을 메모리로 읽을 필요가 없습니다. 단지 메모리를 낭비하고 대기 시간을 추가하며 확장되지 않습니다. 수신 루프와 같은 복사 루프와 말 8k의 버퍼를 사용하십시오.

+0

이렇게하면 TUT를 읽으려고 할 때 서버가 멈 춥니 다. –

관련 문제