我在网上找了一个用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();
}
}
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();
}
}
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)
{
}
}
}
}
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();
}