Example #1
0
  public void start() {
    final LongChannel othis = this;
    beeperHandle =
        heartscheduler.scheduleAtFixedRate(
            new Runnable() {
              public void run() {
                if (reconnectTimes > maxIdle) {
                  stop();
                  ClientCache.remove(othis);
                  setConnected(false);
                  return;
                }
                if ((new Date().getTime() - heartBeat) > 30000) {
                  logger.error("超过三十秒没有响应了");
                  boolean con = reconnect();
                  setConnected(con);
                  logger.info("重连接状态是:" + con);
                } else {
                  if (!channelWriteAble()) {
                    boolean con = reconnect();
                    setConnected(con);
                    logger.info("重连接状态是:" + con);
                    if (con == true) {
                      HeartPro heart = new HeartPro();
                      logger.debug("添加心跳");
                      addMag(heart);
                    }
                  } else {
                    setConnected(true);
                    HeartPro heart = new HeartPro();
                    logger.debug("添加心跳");
                    addMag(heart);
                  }
                }
              }
            },
            10,
            10,
            TimeUnit.SECONDS);

    new Thread() {
      public void run() {
        logger.info("添加监听");
        while (true) {
          Object pro = null;
          try {
            logger.debug("开始取出报文");
            pro = (Object) queue.take();
            logger.debug("结束取出报文:" + pro.getClass());
            if (pro instanceof BaseProtocol) {
              if (channel != null && channel.isWritable()) {
                logger.debug("发送报文");
                channel.write(pro);
              } else {

                if (!(pro instanceof HeartPro)) {
                  addMag((BaseProtocol) pro);
                }
                try {
                  Thread.sleep(1000);
                } catch (Exception e2) {

                }
              }
            } else if (pro instanceof String && pro.equals("~stop~")) {
              try {
                channel.close();
              } catch (Exception e) {

              }
              break;
            }

          } catch (Exception e) {

          }
        }
        logger.info("退出监听");
      }
    }.start();
  }