Socket InputStream在读取块中的字节时出现故障

时间:2015-01-05 22:15:20

标签: java file sockets byte inputstream

我正在通过套接字连接编写简单的文件传输,我遇到了问题 同时以块的字节下载文件。当我一次读取一个字节时一切正常但是当我尝试读取例如512字节的块时,在下载文件的所有字节后(我知道长度归功于我的标题),套接字开始接收一些随机字节并且最终发生了崩溃,因为找到了2x“%”并且服务器尝试计算传入消息的长度,当没有开始时。

 @Override
  public void run() {

      while (client.isConnected() && !client.isClosed() && !client.isInputShutdown()){
          try {
                readResponse();
                clientWriter.write("0%"); /// IF IT CATCHES EXCEPTION SOCKET CLOSED ON THE OTHER SIDE(DON'T KNOW HOW TO CHECK IT IN ANOTHER WAY)
           } 
          catch (IOException e) {
               System.out.println(e.toString());
               return;
           } 
          catch (InterruptedException e) {
               System.out.println(e.toString());
               return;
           } 
      }

   }

private void readResponse() throws IOException, InterruptedException {

       int length = 0;
       int ch;
       FileOutputStream file = new FileOutputStream("holder");
       boolean bWrite = false;
       StringBuilder name = new StringBuilder();
       int percentageCount = 0;
       String filename="";
       length = 0;
       int l = 0;
       int old = 0;
       while ((ch=client.getInputStream().read())!=-1){
           if (!bWrite) {
               name.append(Character.toChars(ch));
           }
           if (ch==37 && !bWrite){
               if (percentageCount<1){
                   percentageCount++;
               } else {
                filename = name.toString();
                length = Integer.parseInt(filename.substring(0,filename.indexOf("%")));
                l = length;
                filename = filename.substring(filename.indexOf("%")+1);
                filename = filename.substring(0,filename.indexOf("%"));
               file = new FileOutputStream(filename);
               bWrite = true;
               break;
               }
           }
       }
       byte[] bytes = new byte[512];
       while (length>=512){
           client.getInputStream().read(bytes, 0, 512);
           file.write(bytes, 0, 512);
           length-=512;
       }
       if (length>0){
           bytes = new byte[length];
           client.getInputStream().read(bytes,0,length);
           file.write(bytes,0,length);
           length = 0;
       }
       file.flush();
       file.close();
    }

1 个答案:

答案 0 :(得分:2)

代码的最后一部分可以更改为(未经测试):

   byte[] bytes = new byte[512];
   InputStream is = client.getInputStream();
   while (length>0) {
       int read = is.read(bytes, 0, Math.min(bytes.length, length));
       if (read > 0) {
         file.write(bytes, 0, read);
         length-=read;
       }
       if (read < 0)
         throw new IOException("end reached before all data read"; 
   }

这正确地检查返回的大小,它避免了两个循环并检查流的结尾。

BTW2:getInputStream()非常重,应该只进行一次(我的示例中的is应该在方法的开头检索,特别是在读取循环之前)。