Example usage for java.nio.channels SelectionKey channel

List of usage examples for java.nio.channels SelectionKey channel

Introduction

In this page you can find the example usage for java.nio.channels SelectionKey channel.

Prototype

public abstract SelectableChannel channel();

Source Link

Document

Returns the channel for which this key was created.

Usage

From source file:net.socket.nio.TimeClientHandle.java

@Override
public void run() {
    try {//from  w w w. j  a va  2 s  . co m
        doConnect();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
    while (!stop) {
        try {
            selector.select(1000);
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> it = selectedKeys.iterator();
            SelectionKey key = null;
            while (it.hasNext()) {
                key = it.next();
                it.remove();
                try {
                    handleInput(key);
                } catch (Exception e) {
                    if (key != null) {
                        key.cancel();
                        if (key.channel() != null) {
                            key.channel().close();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    // ???ChannelPipe??????
    IOUtils.closeQuietly(selector);

}

From source file:oz.hadoop.yarn.api.net.AbstractSocketHandler.java

/**
 * Will stop and disconnect this socket handler blocking until this handler is completely stopped
 * //from  w  w w. j  a v  a2s . c o m
 * @param force
 *       This method performs shutdown by allowing currently running tasks proxied through {@link ContainerDelegate}
 *      to finish while not allowing new tasks to be submitted. If you want to interrupt and kill currently running tasks
 *      set this parameter to 'true'.
 * 
 */
public void stop(boolean force) {
    // for Server it will remove container delegates forcefully or wait if neccessery letting them finish
    this.preStop(force);

    /*
     * close all client sockets which will trigger AM to close its client socket
     * triggering onDisconnect() 
     */
    for (SelectionKey key : new HashSet<>(AbstractSocketHandler.this.selector.keys())) {
        if (this.canClose(key)) {
            Channel channel = key.channel();
            if (channel instanceof SocketChannel) {
                this.closeChannel(channel);
            }
        }
    }

    /* 
     * After closing all clients(AC) sockets containers will terminate and AM
     * will close its client at which point onDisconnect will be triggered and the below
     * wait will succeed. We need this to ensure that we don't exit the application until
     * all remote processes have completely finished and exited.
     */
    this.awaitShutdown();
}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.IncomingConnectionThread.java

private void doRead(SelectionKey key) {

    final IncomingConnection incomingConnection = (IncomingConnection) key.attachment();
    try {/*w  w  w . j a  va  2s.c  o m*/
        incomingConnection.read();
    } catch (EOFException eof) {
        if (incomingConnection.isCloseUnexpected()) {
            final SocketChannel socketChannel = (SocketChannel) key.channel();
            LOG.error("Connection from " + socketChannel.socket().getRemoteSocketAddress()
                    + " was closed unexpectedly");
            incomingConnection.reportTransmissionProblem(key, eof);
        } else {
            incomingConnection.closeConnection(key);
        }
    } catch (IOException ioe) {
        incomingConnection.reportTransmissionProblem(key, ioe);
    } catch (InterruptedException e) {
        // Nothing to do here
    } catch (NoBufferAvailableException e) {
        // There are no buffers available, unsubscribe from read event
        final SocketChannel socketChannel = (SocketChannel) key.channel();
        try {
            final SelectionKey newKey = socketChannel.register(this.selector, 0);
            newKey.attach(incomingConnection);
        } catch (ClosedChannelException e1) {
            incomingConnection.reportTransmissionProblem(key, e1);
        }

        final BufferAvailabilityListener bal = new IncomingConnectionBufferAvailListener(
                this.pendingReadEventSubscribeRequests, key);
        if (!e.getBufferProvider().registerBufferAvailabilityListener(bal)) {
            // In the meantime, a buffer has become available again, subscribe to read event again

            try {
                final SelectionKey newKey = socketChannel.register(this.selector, SelectionKey.OP_READ);
                newKey.attach(incomingConnection);
            } catch (ClosedChannelException e1) {
                incomingConnection.reportTransmissionProblem(key, e1);
            }
        }
    }
}

From source file:ca.wumbo.doommanager.server.ServerManager.java

/**
 * Closes all active connections (does not send out a kill message).
 *//*from www .  j  a  v a2 s .  com*/
private void closeConnections() {
    if (selector.isOpen()) {
        for (SelectionKey key : selector.keys()) {
            key.cancel();
            try {
                key.channel().close();
            } catch (IOException e) {
                log.error("Error closing a timed out client's channel.");
                log.error(e);
            }
        }
    }
}

From source file:oz.hadoop.yarn.api.net.ApplicationContainerServerImpl.java

/**
 * Will stop this server, closing all the remaining connection to Application Container 
 * clients waiting if necessary. /*  ww  w. ja  v a 2s .c  o m*/
 * Closing such connection will force Application Container clients to stop essentially 
 * stopping and exiting Application Containers, thus stopping the entire application.
 * 
 * @param force
 *       boolean flag indicating if this application should be terminated immediately or 
 *       should it shut down gracefully allowing currently running Application Container 
 *       processes to finish.
 */
@Override
void preStop(boolean force) {
    // Need to make a copy so we can remove entries without affecting the global map so it could be cleaned at the end
    Map<SelectionKey, ContainerDelegate> cDelegates = new HashMap<>(this.containerDelegates);
    boolean working = cDelegates.size() > 0;
    while (working) {
        Iterator<SelectionKey> containerSelectionKeys = cDelegates.keySet().iterator();
        while (containerSelectionKeys.hasNext()) {
            SelectionKey selectionKey = containerSelectionKeys.next();
            ContainerDelegate containerDelegate = cDelegates.get(selectionKey);
            containerDelegate.suspend();
            if (!force) {
                if (containerDelegate.available() || !selectionKey.channel().isOpen()) {
                    containerSelectionKeys.remove();
                }
            } else {
                containerSelectionKeys.remove();
            }
        }
        working = cDelegates.size() > 0;
        if (working) {
            if (logger.isTraceEnabled()) {
                logger.trace("Waiting for remaining " + cDelegates.size() + " containers to finish");
            }
            LockSupport.parkNanos(10000000);
        } else {
            this.containerDelegates.clear();
        }
    }
    for (int i = 0; i < this.expectedClientContainers; i++) {
        this.expectedClientContainersMonitor.countDown();
    }
}

From source file:oz.hadoop.yarn.api.net.ApplicationContainerServerImpl.java

/**
 * Unlike the client side the read on the server will happen using receiving thread.
 *//*  www.j a va2s .  c o  m*/
@Override
void read(SelectionKey selectionKey, ByteBuffer replyBuffer) throws IOException {
    ReplyPostProcessor replyCallbackHandler = ((ReplyPostProcessor) this.replyCallbackMap.remove(selectionKey));
    if (logger.isDebugEnabled()) {
        logger.debug("Reply received from " + ((SocketChannel) selectionKey.channel()).getRemoteAddress());
    }
    if (this.replyListener != null) {
        this.replyListener.onReply(replyBuffer);
    }
    replyCallbackHandler.postProcess(replyBuffer);

    if (this.finite) {
        selectionKey.cancel();
        this.closeChannel(selectionKey.channel());
        this.onDisconnect(selectionKey);
    }
}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnectionThread.java

@Override
public void run() {

    while (!isInterrupted()) {

        synchronized (this.pendingConnectionRequests) {

            if (!this.pendingConnectionRequests.isEmpty()) {

                final OutgoingConnection outgoingConnection = this.pendingConnectionRequests.poll();
                try {
                    final SocketChannel socketChannel = SocketChannel.open();
                    socketChannel.configureBlocking(false);
                    final SelectionKey key = socketChannel.register(this.selector, SelectionKey.OP_CONNECT);
                    socketChannel.connect(outgoingConnection.getConnectionAddress());
                    key.attach(outgoingConnection);
                } catch (final IOException ioe) {
                    // IOException is reported by separate thread to avoid deadlocks
                    final Runnable reporterThread = new Runnable() {

                        @Override
                        public void run() {
                            outgoingConnection.reportConnectionProblem(ioe);
                        }//from   ww w. j a va  2s . c  o  m
                    };
                    new Thread(reporterThread).start();
                }
            }
        }

        synchronized (this.pendingWriteEventSubscribeRequests) {

            if (!this.pendingWriteEventSubscribeRequests.isEmpty()) {
                final SelectionKey oldSelectionKey = this.pendingWriteEventSubscribeRequests.poll();
                final OutgoingConnection outgoingConnection = (OutgoingConnection) oldSelectionKey.attachment();
                final SocketChannel socketChannel = (SocketChannel) oldSelectionKey.channel();

                try {
                    final SelectionKey newSelectionKey = socketChannel.register(this.selector,
                            SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                    newSelectionKey.attach(outgoingConnection);
                    outgoingConnection.setSelectionKey(newSelectionKey);
                } catch (final IOException ioe) {
                    // IOException is reported by separate thread to avoid deadlocks
                    final Runnable reporterThread = new Runnable() {

                        @Override
                        public void run() {
                            outgoingConnection.reportTransmissionProblem(ioe);
                        }
                    };
                    new Thread(reporterThread).start();
                }
            }
        }

        synchronized (this.connectionsToClose) {

            final Iterator<Map.Entry<OutgoingConnection, Long>> closeIt = this.connectionsToClose.entrySet()
                    .iterator();
            final long now = System.currentTimeMillis();
            while (closeIt.hasNext()) {

                final Map.Entry<OutgoingConnection, Long> entry = closeIt.next();
                if ((entry.getValue().longValue() + MIN_IDLE_TIME_BEFORE_CLOSE) < now) {
                    final OutgoingConnection outgoingConnection = entry.getKey();
                    closeIt.remove();
                    // Create new thread to close connection to avoid deadlocks
                    final Runnable closeThread = new Runnable() {

                        @Override
                        public void run() {
                            try {
                                outgoingConnection.closeConnection();
                            } catch (IOException ioe) {
                                outgoingConnection.reportTransmissionProblem(ioe);
                            }
                        }
                    };

                    new Thread(closeThread).start();
                }

            }
        }

        try {
            this.selector.select(10);
        } catch (IOException e) {
            LOG.error(e);
        }

        final Iterator<SelectionKey> iter = this.selector.selectedKeys().iterator();

        while (iter.hasNext()) {
            final SelectionKey key = iter.next();

            iter.remove();
            if (key.isValid()) {
                if (key.isConnectable()) {
                    doConnect(key);
                } else {
                    if (key.isReadable()) {
                        doRead(key);
                        // A read will always result in an exception, so the write key will not be valid anymore
                        continue;
                    }
                    if (key.isWritable()) {
                        doWrite(key);
                    }
                }
            } else {
                LOG.error("Received invalid key: " + key);
            }
        }
    }

    // Finally, try to close the selector
    try {
        this.selector.close();
    } catch (IOException ioe) {
        LOG.debug(StringUtils.stringifyException(ioe));
    }
}

From source file:com.l2jfree.network.mmocore.ReadWriteThread.java

private void finishConnection(SelectionKey key) {
    try {//w  ww  .  j a  v a  2s .c o m
        ((SocketChannel) key.channel()).finishConnect();
    } catch (IOException e) {
        @SuppressWarnings("unchecked")
        T con = (T) key.attachment();
        closeConnectionImpl(con, true);
        return;
    }

    // key might have been invalidated on finishConnect()
    if (key.isValid()) {
        key.interestOps(key.interestOps() | SelectionKey.OP_READ);
        key.interestOps(key.interestOps() & ~SelectionKey.OP_CONNECT);
    }
}

From source file:gridool.communication.transport.nio.GridNioServer.java

public void accept(@Nonnull final Selector selector) throws IOException {
    while (!closed && selector.select() > 0) {
        for (Iterator<SelectionKey> iter = selector.selectedKeys().iterator(); iter.hasNext();) {
            SelectionKey key = iter.next();
            iter.remove();/*from   w  w w.  j a  v a2 s  . c  om*/

            if (!key.isValid()) { // Is key closed?
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Non valid key was detected. Key is already closed?");
                }
                continue;
            }

            if (key.isAcceptable()) {
                ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
                handleAccept(serverChannel, selector);
            } else if (key.isReadable()) {
                SocketChannel channel = (SocketChannel) key.channel();
                handleRead(channel, key, sharedReadBuf, notifier, execPool);
            }
        }
    }
    if (LOG.isInfoEnabled()) {
        LOG.info("GridNioServer is going to be closed");
    }
    this.closed = true;
    if (selector.isOpen()) {
        for (SelectionKey key : selector.keys()) {
            NIOUtils.close(key);
        }
        selector.close();
    }
}

From source file:org.apache.nifi.processor.util.listen.dispatcher.SocketChannelDispatcher.java

@Override
public void run() {
    while (!stopped) {
        try {/*from   w  ww . ja  v a 2s.c  o m*/
            int selected = selector.select();
            // if stopped the selector could already be closed which would result in a ClosedSelectorException
            if (selected > 0 && !stopped) {
                Iterator<SelectionKey> selectorKeys = selector.selectedKeys().iterator();
                // if stopped we don't want to modify the keys because close() may still be in progress
                while (selectorKeys.hasNext() && !stopped) {
                    SelectionKey key = selectorKeys.next();
                    selectorKeys.remove();
                    if (!key.isValid()) {
                        continue;
                    }
                    if (key.isAcceptable()) {
                        // Handle new connections coming in
                        final ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        final SocketChannel socketChannel = channel.accept();
                        // Check for available connections
                        if (currentConnections.incrementAndGet() > maxConnections) {
                            currentConnections.decrementAndGet();
                            logger.warn("Rejecting connection from {} because max connections has been met",
                                    new Object[] { socketChannel.getRemoteAddress().toString() });
                            IOUtils.closeQuietly(socketChannel);
                            continue;
                        }
                        logger.debug("Accepted incoming connection from {}",
                                new Object[] { socketChannel.getRemoteAddress().toString() });
                        // Set socket to non-blocking, and register with selector
                        socketChannel.configureBlocking(false);
                        SelectionKey readKey = socketChannel.register(selector, SelectionKey.OP_READ);

                        // Prepare the byte buffer for the reads, clear it out
                        ByteBuffer buffer = bufferPool.poll();
                        buffer.clear();
                        buffer.mark();

                        // If we have an SSLContext then create an SSLEngine for the channel
                        SSLSocketChannel sslSocketChannel = null;
                        if (sslContext != null) {
                            final SSLEngine sslEngine = sslContext.createSSLEngine();
                            sslEngine.setUseClientMode(false);

                            switch (clientAuth) {
                            case REQUIRED:
                                sslEngine.setNeedClientAuth(true);
                                break;
                            case WANT:
                                sslEngine.setWantClientAuth(true);
                                break;
                            case NONE:
                                sslEngine.setNeedClientAuth(false);
                                sslEngine.setWantClientAuth(false);
                                break;
                            }

                            sslSocketChannel = new SSLSocketChannel(sslEngine, socketChannel);
                        }

                        // Attach the buffer and SSLSocketChannel to the key
                        SocketChannelAttachment attachment = new SocketChannelAttachment(buffer,
                                sslSocketChannel);
                        readKey.attach(attachment);
                    } else if (key.isReadable()) {
                        // Clear out the operations the select is interested in until done reading
                        key.interestOps(0);
                        // Create a handler based on the protocol and whether an SSLEngine was provided or not
                        final Runnable handler;
                        if (sslContext != null) {
                            handler = handlerFactory.createSSLHandler(key, this, charset, eventFactory, events,
                                    logger);
                        } else {
                            handler = handlerFactory.createHandler(key, this, charset, eventFactory, events,
                                    logger);
                        }

                        // run the handler
                        executor.execute(handler);
                    }
                }
            }
            // Add back all idle sockets to the select
            SelectionKey key;
            while ((key = keyQueue.poll()) != null) {
                key.interestOps(SelectionKey.OP_READ);
            }
        } catch (IOException e) {
            logger.error("Error accepting connection from SocketChannel", e);
        }
    }
}