java socket客户端上传文件过程中断线,客户端重连,并且服务端继续接收数据

再见也许再也不再见 2014-01-22 12:01:51
服务端正在接收客户端发送的数据,当数据传输到一半时,突然客户端断线,然后客户端重连,连上之后给服务端发送续传请求,服务端接收到续传请求后,返回准许信息,然后客户端再继续发送数据,客户端会从断开的那个字节开始发送,服务端只需要继续接收就可以了,现在我要实现服务端的代码


我的现有代码如下

public void ReceiveData(Socket clientSocket) throws IOException {

//从套接字中获取客户端发过来的数据
InputStream bufIn=clientSocket.getInputStream();

//将输入写入到指定文件
long start = System.nanoTime();

byte buf[]=new byte[10240];

int len=0;

String url = Createfile.url;
FileOutputStream fw=new FileOutputStream(url);

//定义写入缓冲区
System.out.println("正在接收数据...");

int a =0;
int count = 0;



// try{
// //发送心跳包
// clientSocket.sendUrgentData(0);
// }catch(Exception ex){
// //客户端断线
//TODO 我想在这里做一些断线重连的处理,不知道能不能实现
// }



try
{
clientSocket.setSoTimeout(20000);

while((len=bufIn.read(buf))!=-1)

{

a=1;
fw.write(buf, 0, len);
fw.flush();


count++;

System.gc();
}

System.out.println();

}catch (Exception e) {

System.err.println("!!!超时!!!");
}

long end =System.nanoTime();

System.out.println("用时:"+(end-start)/1000000000+"s");

if(a==0){

System.out.println("没有接收到数据");

}else{

Test test = new Test();

int countE_anlilianpic = test.count(url, "E_anlilianPic");

if(countE_anlilianpic==0){

System.err.println("数据接收不完整");

}else{

count = test.count(url, "##$##");

System.out.println("共接收"+count+"张照片");
}



}

ReceiveData_3.is.close();
ReturnData_6.outputStream.close();
fw.close();
bufIn.close();
ListenPort_1.count--;
System.out.println("------------------已释放资源------------------");
clientSocket.close();
}
...全文
415 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
引用 3 楼 bigc2001 的回复:
续传就是客户端记录已经发送的字节位置,下次上传时从该位置读取并发送,而接收端负责组装。 两个关键:识别是哪一个文件、改文件已经传输的位置。
这个已经找到思路了,thanks
  • 打赏
  • 举报
回复
求高手指教啊,怎么没人
比特灵 2014-01-22
  • 打赏
  • 举报
回复
续传就是客户端记录已经发送的字节位置,下次上传时从该位置读取并发送,而接收端负责组装。 两个关键:识别是哪一个文件、改文件已经传输的位置。

62,615

社区成员

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

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