Example #1
0
  /**
   * Method run.
   *
   * @see java.lang.Runnable#run()
   */
  @Override
  public void run() {
    int totalKeys = 0;
    Set<SelectionKey> keys = null;
    Iterator<SelectionKey> itr = null;
    Iterator<MMOConnection<T>> conItr = null;
    SelectionKey key = null;
    MMOConnection<T> con = null;
    long currentMillis = 0L;

    // main loop
    for (; ; ) {
      try {

        if (isShuttingDown()) {
          closeSelectorThread();
          break;
        }

        currentMillis = System.currentTimeMillis();

        conItr = _connections.iterator();
        while (conItr.hasNext()) {
          con = conItr.next();
          if (con.isPengingClose()) {
            if (!con.isPendingWrite() || ((currentMillis - con.getPendingCloseTime()) >= 10000L)) {
              closeConnectionImpl(con);
              continue;
            }
          }
          if (con.isPendingWrite()) {
            if ((currentMillis - con.getPendingWriteTime()) >= _sc.INTEREST_DELAY) {
              con.enableWriteInterest();
            }
          }
        }

        totalKeys = getSelector().selectNow();

        if (totalKeys > 0) {
          keys = getSelector().selectedKeys();
          itr = keys.iterator();

          while (itr.hasNext()) {
            key = itr.next();
            itr.remove();

            if (key.isValid()) {
              try {
                if (key.isAcceptable()) {
                  acceptConnection(key);
                  continue;
                } else if (key.isConnectable()) {
                  finishConnection(key);
                  continue;
                }

                if (key.isReadable()) {
                  readPacket(key);
                }
                if (key.isValid()) {
                  if (key.isWritable()) {
                    writePacket(key);
                  }
                }
              } catch (CancelledKeyException cke) {

              }
            }
          }
        }

        try {
          Thread.sleep(_sc.SLEEP_TIME);
        } catch (InterruptedException ie) {

        }
      } catch (IOException e) {
        _log.error("Error in " + getName(), e);

        try {
          Thread.sleep(1000L);
        } catch (InterruptedException ie) {

        }
      }
    }
  }