2016-05-17 46 views
0

我有一個客戶端和服務器程序,應該這樣工作: 客戶端類型在命令行(stdin)中的文件名和服務器通過套接字發送客戶端文件數據。 發送另一個名稱和另一個文件的客戶端類型。Java一次發送多個文件

但是,我目前只能夠得到一個文件發送。第二次輸入文件名時,它不會進入我的客戶端中的while循環:「while((count = in.read(buffer))> 0){」

Client(variable「fromUser」從服務器請求的文件的文件名,outCommands的是,這個文件名發送到服務器傳出的數據流):

while(true) { 
       fromUser = stdIn.readLine(); 
       if (fromUser != null) { 
        outCommands.println(fromUser); 

        while ((count = in.read(buffer)) > 0) { 
         String fileName = "downloaded" + in.readUTF(); 
         OutputStream fileOut = new FileOutputStream(fileName); 

         try 
         { 
          fileOut.write(buffer, 0, count); 
          fileOut.flush(); 
         } catch (IOException e) { 

         } 
         fileOut.close(); 
         break; 
        } 
       } else if (fromUser.equals("Stop")) { 
        in.close(); 
        stdIn.close(); 
        dlSocket.close(); 
       } 
      } 

服務器(「DLP」是服務器套接字,「走出去」是即將離任的數據流) :

while(!(fileD = in.readLine()).equals(null)) { 
       System.out.println("Line read:" + fileD); 

      // Load file 
      File file = new File(fileD); 
       System.out.println(file.getAbsolutePath()); 

       System.out.println("File created..."); 
      InputStream fileIn = new FileInputStream(file); 

      outputLine = dlp.processInput(null); 

      byte[] buffer = new byte[8192]; 
      int count; 
       while ((count = fileIn.read(buffer)) > 0) { 
        System.out.println("Beginning file transfer"); 
        out.write(buffer, 0, count); 
       } 

       System.out.println("Completed file transfer"); 
       // Write filename to out socket 
       out.writeUTF(file.getName()); 
       out.writeLong(file.length()); 
       out.flush(); 
      } 

      in.close(); 
      out.close(); 
      clientSocket.close(); 

有人可以幫我弄清楚爲什麼會發生這種情況嗎?我不明白爲什麼一旦服務器通過客戶端請求發送第二個文件後,「count = in.read(buffer)」不會大於零。

源:https://github.com/richardrl/downloader/tree/master/src/main/java

+0

打破不是一個問題http://stackoverflow.com/questions/12393231/break-statement-inside-two-while-loops –

+0

該代碼有許多問題,從讀取整個文件的假設開始在一次讀取中,並擴展到寫入長度並且從不讀取它,並且在文件之後而不是之前寫入文件名和長度,這是兩者都需要的時間。在副本中查看我的答案。 – EJP

+0

具體來說,「count = in.read(buffer)」在第一個文件後達到流尾時不能爲非零。這就是爲什麼你需要知道文件發送前的長度,所以你知道有多少字節要讀取。這段代碼將在第二個'readUTF()'上拋出'EOFException'。 – EJP

回答

2

因爲你在while循環它打破了,不回去的循環條件下使用break。 而不是break你應該使用continue - 甚至更好,去掉它,因爲它是在一個循環的範圍的結束不必要的(即將反正再次重申):

while ((count = in.read(buffer)) > 0) { 
    String fileName = "downloaded" + in.readUTF(); 
    OutputStream fileOut = new FileOutputStream(fileName); 
    try { 
     fileOut.write(buffer, 0, count); 
     fileOut.flush(); 
    } catch (IOException e) { 

    } 
    fileOut.close(); 
    // continue; // not needed 
} 

continue循環執行行時停止並且要執行的下一行是循環條件。如上所述,這不是必需的,因爲您即將重新進行迭代。

+0

當我取出中斷時,它甚至不執行這部分代碼:「if(fromUser!= null)outCommands.println(fromUser);」當我輸入第二個文件名到stdin – Richard

+0

繼續也不起作用:( – Richard

+0

我更新了主文章的文件 – Richard