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:org.pvalsecc.comm.MultiplexedServer.java

private void createNewClientConnection(SelectionKey key) {
    SocketChannel socket = null;//w w w . java 2s.  c o  m
    try {
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
        socket = serverSocketChannel.accept();
    } catch (IOException e) {
        LOGGER.error("Cannot accept the connection from a new client", e);
        SystemUtilities.safeClose(socket);
        return;
    }

    SelectionKey newKey;
    try {
        socket.configureBlocking(false);
        newKey = socket.register(selector, SelectionKey.OP_READ);
    } catch (IOException e) {
        LOGGER.error("Cannot add a new client socket to the selector", e);
        SystemUtilities.safeClose(socket);
        return;
    }

    ServerConnection connection = newConnection(newKey);
    newKey.attach(connection);

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("[" + threadName + "] New connection from " + connection);
    }
}

From source file:org.apache.axis2.transport.udp.IODispatcher.java

/**
 * Remove an endpoint. This causes the corresponding UDP socket to be
 * closed.//  ww  w .  ja  v  a2 s  .c o m
 * 
 * @param endpoint the endpoint description
 * @throws IOException if an error occurred when closing the socket
 */
public void removeEndpoint(final Endpoint endpoint) throws IOException {
    execute(new SelectorOperation() {
        @Override
        public void doExecute(Selector selector) throws IOException {
            Iterator<SelectionKey> it = selector.keys().iterator();
            while (it.hasNext()) {
                SelectionKey key = it.next();
                Endpoint endpointForKey = (Endpoint) key.attachment();
                if (endpoint == endpointForKey) {
                    key.cancel();
                    key.channel().close();
                    break;
                }
            }
        }
    });
}

From source file:org.apache.catalina.cluster.tcp.ReplicationListener.java

public void listen() throws Exception {
    doListen = true;/*  www.ja v  a  2  s. com*/
    // allocate an unbound server socket channel
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    // Get the associated ServerSocket to bind it with
    ServerSocket serverSocket = serverChannel.socket();
    // create a new Selector for use below
    Selector selector = Selector.open();
    // set the port the server channel will listen to
    serverSocket.bind(new InetSocketAddress(bind, port));
    // set non-blocking mode for the listening socket
    serverChannel.configureBlocking(false);
    // register the ServerSocketChannel with the Selector
    serverChannel.register(selector, SelectionKey.OP_ACCEPT);
    while (doListen) {
        // this may block for a long time, upon return the
        // selected set contains keys of the ready channels
        try {

            //System.out.println("Selecting with timeout="+timeout);
            int n = selector.select(timeout);
            //System.out.println("select returned="+n);
            if (n == 0) {
                continue; // nothing to do
            }
            // get an iterator over the set of selected keys
            Iterator it = selector.selectedKeys().iterator();
            // look at each key in the selected set
            while (it.hasNext()) {
                SelectionKey key = (SelectionKey) it.next();
                // Is a new connection coming in?
                if (key.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel channel = server.accept();
                    registerChannel(selector, channel, SelectionKey.OP_READ,
                            new ObjectReader(channel, selector, callback));
                }
                // is there data to read on this channel?
                //System.out.println("key readable="+key.isReadable());
                if (key.isReadable()) {
                    readDataFromSocket(key);
                } else {
                    //System.out.println("This shouldn't get called");
                    key.interestOps(key.interestOps() & (~key.OP_WRITE));
                }

                // remove key from selected set, it's been handled
                it.remove();
            }
            //System.out.println("Done with loop");
        } catch (java.nio.channels.CancelledKeyException nx) {
            log.warn("Replication client disconnected, error when polling key. Ignoring client.");
        } catch (Exception x) {
            log.error("Unable to process request in ReplicationListener", x);
        }

    } //while
    serverChannel.close();
    selector.close();
}

From source file:voldemort.common.nio.AbstractSelectorManager.java

public void close() {
    // Attempt to close, but if already closed, then we've been beaten to
    // the punch...
    if (!isClosed.compareAndSet(false, true))
        return;/*  w w w.j  a  va  2 s  .  c  o  m*/

    try {
        for (SelectionKey sk : selector.keys()) {
            try {
                if (logger.isTraceEnabled())
                    logger.trace("Closing SelectionKey's channel");

                sk.channel().close();

                Object attachment = sk.attachment();
                if (attachment instanceof Closeable) {
                    IOUtils.closeQuietly((Closeable) attachment);
                }
            } catch (Exception e) {
                if (logger.isEnabledFor(Level.WARN))
                    logger.warn(e.getMessage(), e);
            }

            try {
                if (logger.isTraceEnabled())
                    logger.trace("Cancelling SelectionKey");

                sk.cancel();
            } catch (Exception e) {
                if (logger.isEnabledFor(Level.WARN))
                    logger.warn(e.getMessage(), e);
            }
        }
    } catch (Exception e) {
        if (logger.isEnabledFor(Level.WARN))
            logger.warn(e.getMessage(), e);
    }

    try {
        selector.close();
    } catch (Exception e) {
        if (logger.isEnabledFor(Level.WARN))
            logger.warn(e.getMessage(), e);
    }
}

From source file:com.byteatebit.nbserver.task.ReadDelimitedMessageTask.java

protected void read(SelectionKey selectionKey, Consumer<List<String>> callback,
        Consumer<Exception> exceptionHandler) {
    try {//from www  .  j a v a  2s . c  o  m
        if (!selectionKey.isValid() || !selectionKey.isReadable())
            return;
        byteBuffer.clear();
        int bytesRead = ((ReadableByteChannel) selectionKey.channel()).read(byteBuffer);
        if (bytesRead < 0) {
            LOG.warn(
                    "End of stream reached.  Deregistering interest in reads on the selection key invoking exception handler.");
            invokeExceptionHandler(selectionKey, exceptionHandler, new EOFException("End of stream"));
            return;
        }
        byteBuffer.flip();
        if (byteBuffer.remaining() + messageBuffer.size() > maxMessageSize) {
            LOG.error("Max message size of " + maxMessageSize
                    + " bytes exceeded.  Deregistering interest in reads on the selection key invoking exception handler.");
            invokeExceptionHandler(selectionKey, exceptionHandler,
                    new IllegalStateException("Max message size of " + maxMessageSize + " bytes exceeded"));
            return;
        }
        while (byteBuffer.hasRemaining())
            messageBuffer.write(byteBuffer.get());
        String messagesString = messageBuffer.toString(charset);
        messageBuffer.reset();
        List<String> messages = new ArrayList<>();
        for (String message : splitter.split(messagesString))
            messages.add(message);
        messageBuffer.write(messages.remove(messages.size() - 1).getBytes(charset));
        if (!messages.isEmpty()) {
            selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_READ);
            callback.accept(messages);
        }
    } catch (Exception e) {
        LOG.error("ReadDelimitedMessage task failed", e);
        invokeExceptionHandler(selectionKey, exceptionHandler, e);
    }
}

From source file:org.apache.synapse.transport.udp.IODispatcher.java

/**
 * Remove an endpoint. This causes the corresponding UDP socket to be
 * closed./*  w  ww.  jav  a  2s  .  c  om*/
 * 
 * @param serviceName the name of the service corresponding to
 *                    the endpoint
 * @throws IOException if an error occurred when closing the socket
 */
public void removeEndpoint(final String serviceName) throws IOException {
    execute(new SelectorOperation() {
        @Override
        public void doExecute(Selector selector) throws IOException {
            Iterator<SelectionKey> it = selector.keys().iterator();
            while (it.hasNext()) {
                SelectionKey key = it.next();
                Endpoint endpoint = (Endpoint) key.attachment();
                if (serviceName.equals(endpoint.getService().getName())) {
                    key.cancel();
                    key.channel().close();
                    break;
                }
            }
        }
    });
}

From source file:org.pvalsecc.comm.MultiplexedServer.java

private void readyToReceive(SelectionKey key) {
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    //noinspection ConstantConditions
    SocketChannel socket = (SocketChannel) key.channel();
    ServerConnection connection = (ServerConnection) key.attachment();

    int size;//ww  w  . j a  v a  2 s . co  m
    try {
        size = socket.read(buffer);
    } catch (IOException e) {
        //message logging and call to "closed" is done in "error" method
        connection.error("Cannot receive data", e);
        key.cancel();
        SystemUtilities.safeClose(socket);
        return;
    }

    if (size >= 0) {
        if (size != buffer.position()) {
            throw new RuntimeException(
                    "[" + threadName + "] Inconsistent buffer: " + size + "!=" + buffer.position());
        }
        nbBytesReceived += size;
        nbReceived++;
        buffer.flip();
        connection.received(buffer);
    } else {
        LOGGER.info("[" + threadName + "] Connection closed by " + connection);
        connection.closed();
        key.cancel();
    }
}

From source file:jp.queuelinker.system.net.SelectorThread.java

private void finalCleanUp() {
    Iterator<SelectionKey> iter = selector.keys().iterator();
    while (iter.hasNext()) {
        SelectionKey key = iter.next();
        try {/*from w  w w .java 2s . c  o m*/
            key.channel().close();
        } catch (IOException e) {
            logger.info("An IOException happened while closing a channel: " + key.channel().toString());
        }
    }

    try {
        selector.close();
    } catch (IOException e) {
        logger.info("An IOException happened while closing a selector");
    }
}

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

@Override
public void run() {

    while (!this.isInterrupted()) {

        synchronized (this.pendingReadEventSubscribeRequests) {
            while (!this.pendingReadEventSubscribeRequests.isEmpty()) {
                final SelectionKey key = this.pendingReadEventSubscribeRequests.poll();
                final IncomingConnection incomingConnection = (IncomingConnection) key.attachment();
                final SocketChannel socketChannel = (SocketChannel) key.channel();

                try {
                    final SelectionKey newKey = socketChannel.register(this.selector, SelectionKey.OP_READ);
                    newKey.attach(incomingConnection);
                } catch (ClosedChannelException e) {
                    incomingConnection.reportTransmissionProblem(key, e);
                }//ww w.ja  va2  s .com
            }
        }

        try {
            this.selector.select(500);
        } 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.isReadable()) {
                    doRead(key);
                } else if (key.isAcceptable()) {
                    doAccept(key);
                } else {
                    LOG.error("Unknown key: " + key);
                }
            } else {
                LOG.error("Received invalid key: " + key);
            }
        }
    }

    // Do cleanup, if necessary
    if (this.listeningSocket != null) {
        try {
            this.listeningSocket.close();
        } catch (IOException ioe) {
            // Actually, we can ignore this exception
            LOG.debug(ioe);
        }
    }

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

From source file:org.reunionemu.jreunion.server.Network.java

@Override
public void run() {
    logger.info("network thread starting");
    while (true) {
        try {/*w  ww.  j av  a2s.c o  m*/
            // See if we've had any activity -- either an incoming connection,
            // or incoming data on an existing connection
            int num = selector.select();
            if (num == 0) {
                // we need synchronize here otherwise we might block again before we were able to change the selector
                synchronized (this) {
                    continue;
                }
            }

            // If we don't have any activity, loop around and wait again
            // Get the keys corresponding to the activity
            // that has been detected, and process them one by one

            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> it = keys.iterator();
            while (it.hasNext()) {
                // Get a key representing one of bits of I/O activity
                SelectionKey key = it.next();
                if (!key.isValid())
                    continue;

                SelectableChannel selectableChannel = key.channel();
                // What kind of activity is it?
                if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {

                    // It's an incoming connection.
                    // Register this socket with the Selector
                    // so we can listen for input on it                  

                    SocketChannel clientSocketChannel = ((ServerSocketChannel) selectableChannel).accept();

                    processAccept(clientSocketChannel);

                } else {
                    SocketChannel socketChannel = (SocketChannel) selectableChannel;

                    if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {

                        // It's incoming data on a connection, so process it
                        boolean ok = processInput(socketChannel);

                        // If the connection is dead, then remove it
                        // from the selector and close it
                        if (!ok) {
                            LoggerFactory.getLogger(Network.class).info("Client Connection Lost");
                            key.cancel();
                            disconnect(socketChannel);
                        }

                    } else if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {

                        boolean ok = processOutput(socketChannel);
                        if (ok) {
                            socketChannel.register(selector, SelectionKey.OP_READ);
                        }
                    }
                }
            }
            // We remove the selected keys, because we've dealt with them.
            keys.clear();

        } catch (Exception e) {
            if (e instanceof ClosedSelectorException || e instanceof InterruptedException)
                return;
            LoggerFactory.getLogger(Network.class).error("Error in network", e);
        }
    }

}