Socket传输文件的问题,急...

free131 2005-11-16 02:31:50
我在网上找了一个用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();
}
}
...全文
122 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
free131 2005-11-17
  • 打赏
  • 举报
回复
ding
free131 2005-11-17
  • 打赏
  • 举报
回复
我又测试了一下,发现问题出在接收的时候,可能是收到的数据太快了,前一次的数据还没有处理,下一次数据又来了,这样就造成了数据丢失,以下是接收数据的部分,请大家看看该如何修改:
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();
}
f_acme 2005-11-17
  • 打赏
  • 举报
回复
我以前是这样做的.
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)
{
}

}
}
}
  • 打赏
  • 举报
回复
你在收数据的时候加个Thread.sleep(times)试试,应该可以延缓处理
free131 2005-11-17
  • 打赏
  • 举报
回复
ding
Mervyn 2005-11-16
  • 打赏
  • 举报
回复
加大bufferlength的容量应该可以
free131 2005-11-16
  • 打赏
  • 举报
回复
ding

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧