Java一次发送多个文件

Java一次发送多个文件

问题描述:

我有一个客户端和服务器程序,应该这样工作: 客户端类型在命令行(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://*.com/questions/12393231/break-statement-inside-two-while-loops –

+0

该代码有许多问题,从读取整个文件的假设开始在一次读取中,并扩展到写入长度并且从不读取它,并且在文件之后而不是之前写入文件名和长度,这是两者都需要的时间。在副本中查看我的答案。 – EJP

+0

具体来说,“count = in.read(buffer)”在第一个文件后达到流尾时不能为非零。这就是为什么你需要知道文件发送前的长度,所以你知道有多少字节要读取。这段代码将在第二个'readUTF()'上抛出'EOFException'。 – EJP

因为你在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