Пример #1
0
  /**
   * Serves the incoming connections.
   *
   * @throws IOException
   * @throws DirectoryException
   */
  private void serveIncomingConnections() throws IOException, DirectoryException {
    int selectorState = selector.select();

    // We can't rely on return value of select to determine if any keys
    // are ready.
    // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4850373
    for (Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
        iterator.hasNext(); ) {
      SelectionKey key = iterator.next();
      iterator.remove();
      if (key.isAcceptable()) {
        // Accept the new client connection.
        ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
        SocketChannel clientChannel = serverChannel.accept();
        if (clientChannel != null) {
          acceptConnection(clientChannel);
        }
      }

      if (selectorState == 0 && enabled && !shutdownRequested && logger.isTraceEnabled()) {
        // Selected keys was non empty but select() returned 0.
        // Log warning and hope it blocks on the next select() call.
        logger.trace(
            "Selector.select() returned 0. "
                + "Selected Keys: %d, Interest Ops: %d, Ready Ops: %d ",
            selector.selectedKeys().size(), key.interestOps(), key.readyOps());
      }
    }
  }
Пример #2
0
  /**
   * Cleans up the contents of the selector, closing any server socket channels that might be
   * associated with it. Any connections that might have been established through those channels
   * should not be impacted.
   */
  private void cleanUpSelector() {
    try {
      for (SelectionKey key : selector.keys()) {
        try {
          key.cancel();
        } catch (Exception e) {
          logger.traceException(e);
        }

        try {
          key.channel().close();
        } catch (Exception e) {
          logger.traceException(e);
        }
      }
    } catch (Exception e) {
      logger.traceException(e);
    }
  }