我在网上找了一个用Socket在客户端和服务器端传输文件的程序,发现在循环传递文件数据的时候,如果文件比较大,会出现数据丢失,比如传递一个8M的文件到服务器,最后服务器收到的文件只有6M多,有时候还会死在这个循环这里,以下就是循环的代码,请帮忙看看,分不够我再加!
public void upFileData(String strFilePath){
try{
File file = new File(strFilePath);
fileInputStream = new FileInputStream(file);
int iInputLength = 0;
String strInputLength;
byte[] readBytes = new byte[bufferlength];
//Send file data to server with loop
while ( (iInputLength = fileInputStream.read(readBytes, 0,bufferlength)) != -1){
strInputLength = PublicFunction.formatLength(iInputLength);
byte[] outBytes = PublicFunction.makepackage("UPDATAS", strInputLength, readBytes);
outputStream.write(outBytes, 0, outBytes.length);
outputStream.flush();
}
//File data send over, then send ENDFILE order to server
outputStream.write(PublicFunction.makepackage("ENDFILE", "00001",new byte[1]));
outputStream.flush();
}
catch (Exception e){
mylog.warning("Client upload file to server wrong!");
e.printStackTrace();
}
}

解决方案 »

  1.   

    加大bufferlength的容量应该可以
      

  2.   

    我以前是这样做的.
    public void acceptFile (BufferedOutputStream bos,Socket sk)
      {
    //线程运行实体 
       BufferedReader in = null;
       DataInputStream ins = null;
       try{
         InputStreamReader isr;
         isr = new InputStreamReader (sk.getInputStream ());
         in = new BufferedReader (isr);
         ins = new DataInputStream(new BufferedInputStream(sk.getInputStream()));
                byte[] buf= new byte[65536];
                indata=0; datacount = 0;
                
                inti=System.currentTimeMillis();
                indata=ins.read(buf);
                datacount+=indata;
         while(indata!=-1){
    bos.write(buf,0,indata);
           bos.flush();
           indata = ins.read(buf);
          
         }
        
         if(bos!=null) bos.close(); 
         if(ins!=null) ins.close();
        
        }catch (IOException e)
        {
           System.out.println (e.toString ()+"传输出现异常");
        }
        finally
        {
           try{
            if (in != null)
              in.close ();
            if (sk != null)
                sk.close (); 
        }catch (IOException e)
         {
         }
        
        }
      }
    }
      

  3.   

    我又测试了一下,发现问题出在接收的时候,可能是收到的数据太快了,前一次的数据还没有处理,下一次数据又来了,这样就造成了数据丢失,以下是接收数据的部分,请大家看看该如何修改:
    else if (clientOrder.equals("UPDATAS")){ 
    //this package is the upload datas
    mylog.info("Reciving file datas......");
    int iDataLength = Integer.parseInt(new String(inputBytes, 7, 5));

    fileOutputStream.write(inputBytes, 12, iDataLength);
    fileOutputStream.flush();
    }
      

  4.   

    你在收数据的时候加个Thread.sleep(times)试试,应该可以延缓处理