java 网络程序 自动定时连接

来源:互联网 发布:淘宝上买ae片头模板 编辑:程序博客网 时间:2024/05/29 17:39

为了备忘.

 

 

java客户端使用TCP/IP协议连接服务器,服务器有数据(可用数据,非交互信令)即发送给客户端.

 

客户端在一定时间内没有收到数据,在无法判断是服务器无数据或是网络连接不可达时,重新连接.

 

设置socket的keepAlive 超时时间 和 捕获连接异常 作为判断条件.

 

connPbx(){


  try{


  if(s != null)
     s.close(); 


  s     = new Socket(IP,PORT);//连接pbx服务器


  if(s  == null){
     connPbx();
  }


  if(s.isConnected()) {
     s.setKeepAlive(true);
     s.setSoTimeout(60000*3);
  
  foStream                   = new FileWriter(fileTxt,true);//保存数据到文件末尾,而不是覆盖文件
  BufferedWriter bfout = new BufferedWriter(foStream);
  bf                              = new BufferedReader(new InputStreamReader(s.getInputStream()));
  out                            = new PrintWriter(bfout);
  String huadan           = null;


  while( (huadan = bf.readLine()) != null)
  { 
       out.write(huadan+"/r/n");//写入文件
       out.flush();   
  }  

  }  
  }catch(Exception Te){
    // 超时、网络异常 重连 
    try {


     if(out != null)
        out.close();


     if(s    != null)
        s.close();


     connPbx(); 


    } catch (IOException e) {
     e.printStackTrace();
    }
   
  }
 }