Java-socket多个IP断开重新链接问题

第一:自己封装的Socket

public class Session extends Socket {

    private InputStream in = null;
    private OutputStream out = null;
    private DataInputStream dis = null;
    private DataOutputStream dos = null;

    public Session(String ip, int port) throws UnknownHostException, IOException {
        super(ip, port);
    }
    
    public Session() {
        super();
    }
    
    public InputStream getInputStream() {
        if(in==null) {
            try {
                in = super.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return in;
    }
    
    public DataInputStream getDataInputStream() {
        if(dis==null) {
            dis = new DataInputStream(getInputStream());
        }
        
        return dis;
    }

    public OutputStream getOutputStream() {
        if(out==null) {
            try {
                out = super.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return out;
    }
    
    public DataOutputStream getDataOutputStream() {
        if(dos==null) {
            dos = new DataOutputStream(getOutputStream());
        }
        return dos;
    }
    
    
    public void disConnect() {
        try {
            if (dos != null) {
                dos.close();
            }
            if(dis!=null) {
                dis.close();
            }
            if(in!=null) {
                in.close();
            }
            if(out!=null) {
                out.close();
            }
            this.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
第二:读取config.properties中配置的多个ip地址,连接

public class SessionCon {
    int t,k;
    int port = Integer.parseInt(Constants.port);
    String ip = "";
    String[] ipArr = Constants.ip.split(",");

    /**
     * session链接配置文件中的IP和端口,
     * 如果链接成功返回session,链接不成功继续;链接下一个IP和端口
     * 如果都链接不成功,弹窗提示信息
     * @return
     */
    public Session getConnect() {
        Session eventSession = null;
        System.out.println("IP地址个数=="+ipArr.length);
        for(int i = 0 ; i<ipArr.length; i++) {
            try {
                    ip = ipArr[i];
                    System.out.println("ip=" + ip);
                    eventSession = new Session(ip, port);
                    t=i;//如果链接成功,用t进行标识该IP下标
                    break;
            } catch (Exception e) {
                if (i==ipArr.length-1) {
                    System.out.println(ipArr[i]+"链接失败");
                    JFrame jframe = new JFrame();
                    JOptionPane.showMessageDialog(jframe, "IP地址链接异常!");
                    return null;
                }else {
                    System.out.println(ip+"链接失败");
                    continue;
                }
            }
        }
        return eventSession;
        
    }
    
    

    /**
     * 链接成功的用t进行标示,直接定位读取链接成功的IP
     * @return
     */
    public Session setConnect(){
        for(int k=0;k<ipArr.length;k++){
            if(t==k){
                try {
                    Session sessionZero = new Session(ipArr[k], port);
                    return sessionZero;
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    
}

第三:初始化长连接,设置监听器进行监听链接状态

public void connect() {
        
         eventSession=sCon.getConnect();
        if(eventSession!=null){
            eventOneInfoSession=sCon.setConnect();//eventSessioin不为NULL说明IP连接上,调用sCon.setCon()来直接链接到那个IP
            DataHandle.sendEventOneInfo(eventOneInfoSession);
            eventOneInfo=DataHandle.getEventOneInfo(eventOneInfoSession);
            Model();
            
            eventThreeInfoSession = sCon.setConnect();
            DataHandle.sendEventThreeInfo(eventThreeInfoSession);
            eventThreeInfo=DataHandle.getEventThreeInfo(eventThreeInfoSession);//接收事件三数据
            
            eventFourInfoSession = sCon.setConnect();
            DataHandle.sendEventFourInfo(eventFourInfoSession);
            eventFourInfo=DataHandle.getEventFourInfo(eventFourInfoSession);//接收事件四数据
            
        }/*else{
            JFrame jrame=new JFrame();
            JOptionPane.showMessageDialog(jrame, "IP地址异常!");
        }*/
        
        /**
         * flad用来标识timerTask,为true时触发定时器
         */
        if(flad){
            // 定时读取输入输出信息
            timerTask();
        }

    }

//定时器内设置监听

    /*
     * 定时器
     */
    public void timerTask() {
        Timer timer = new Timer(false);
        TimerTask task = new TimerTask() {
            @Override
            public synchronized void run() {
                
                close=isServerClose(eventOneInfoSession);//监听session的链接状态,断开返回true,未断开返回false
//                System.out.println("定时器内**close2**="+close);
                
                    while(close){
                    try {
                        eventSession.close();//关闭eventSession以便下面运行connect重启
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                    flad=false;
                    connect();
                    close=isServerClose(eventOneInfoSession);//监听session的链接状态,断开返回true,未断开返回false
//                    System.out.println("while体内**close**=="+close);
                }


                DataHandle.sendEventOneInfo(eventOneInfoSession);
                eventOneInfo=DataHandle.getEventOneInfo(eventOneInfoSession);//接收事件一数据
                
                DataHandle.sendEventThreeInfo(eventThreeInfoSession);
                eventThreeInfo=DataHandle.getEventThreeInfo(eventThreeInfoSession);//接收事件三数据
                refreshYiChangTable();//刷新异常服务的方法
                    
                
                DataHandle.sendEventFourInfo(eventFourInfoSession);
                eventFourInfo=DataHandle.getEventFourInfo(eventFourInfoSession);//接收事件四数据
                refreshFuZaiTable();//刷新资源负载信息的方法 
//                System.out.println("测试刷新");
            }
        };
        long delay = 0;
        long period = 5000;//五秒
        // 启动定时任务立即执行一次,然后每隔五秒执行一次
        timer.scheduleAtFixedRate(task, delay, period);
    }

//写判断session是否断开的方法

  /** 
      * 判断是否断开连接,断开返回true,没有返回false 
      * @param socket 
      * @return 
      */  
      public Boolean isServerClose(Socket socket){  
         try{  
          socket.sendUrgentData(0);//发送1个字节的紧急数据,默认情况下,服务器端没有开启紧急数据处理,不影响正常通信  
          return false;  
         }catch(Exception se){  
          return true;  
         }  
      }  

转载于:https://my.oschina.net/gamuzaer/blog/700229

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值