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:com.offbynull.portmapper.common.UdpCommunicator.java

@Override
protected void run() throws Exception {
    ByteBuffer recvBuffer = ByteBuffer.allocate(1100);

    while (true) {
        selector.select();/*from  ww  w  .j  a va  2 s .com*/
        if (stopFlag) {
            return;
        }

        for (DatagramChannel channel : sendQueue.keySet()) {
            if (!sendQueue.get(channel).isEmpty()) {
                channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
            } else {
                channel.register(selector, SelectionKey.OP_READ);
            }
        }

        for (SelectionKey key : selector.selectedKeys()) {
            if (!key.isValid()) {
                continue;
            }

            DatagramChannel channel = (DatagramChannel) key.channel();

            if (key.isReadable()) {
                recvBuffer.clear();
                InetSocketAddress incomingAddress = (InetSocketAddress) channel.receive(recvBuffer);
                recvBuffer.flip();
                for (UdpCommunicatorListener listener : listeners) {
                    try {
                        listener.incomingPacket(incomingAddress, channel, recvBuffer.asReadOnlyBuffer());
                    } catch (RuntimeException re) { // NOPMD
                        // do nothing
                    }
                }
            } else if (key.isWritable()) {
                LinkedBlockingQueue<ImmutablePair<InetSocketAddress, ByteBuffer>> queue = sendQueue
                        .get(channel);
                ImmutablePair<InetSocketAddress, ByteBuffer> next = queue.poll();

                if (next != null) {
                    try {
                        channel.send(next.getValue(), next.getKey());
                    } catch (RuntimeException re) { // NOPMD
                        // do nothing
                    }
                }
            }
        }
    }
}

From source file:org.openhab.io.transport.cul.internal.network.CULNetworkHandlerImpl.java

private void processWrite(SelectionKey key) throws IOException {
    WritableByteChannel ch = (WritableByteChannel) key.channel();
    synchronized (writeBuf) {
        writeBuf.flip();//from   ww  w.  j  a  v  a 2 s  .co  m

        int bytesOp = 0, bytesTotal = 0;
        while (writeBuf.hasRemaining() && (bytesOp = ch.write(writeBuf)) > 0) {
            bytesTotal += bytesOp;
        }
        logger.debug("Written {} bytes to the network", bytesTotal);

        if (writeBuf.remaining() == 0) {
            key.interestOps(key.interestOps() ^ SelectionKey.OP_WRITE);
        }

        if (bytesTotal > 0) {
            writeBuf.notify();
        } else if (bytesOp == -1) {
            logger.info("peer closed write channel");
            ch.close();
        }

        writeBuf.compact();
    }
}

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

private void doConnect(SelectionKey key) {

    final OutgoingConnection outgoingConnection = (OutgoingConnection) key.attachment();
    final SocketChannel socketChannel = (SocketChannel) key.channel();
    try {//from ww  w  . j a va 2s  .  co  m
        while (!socketChannel.finishConnect()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
                LOG.error(e1);
            }
        }

        final SelectionKey channelKey = socketChannel.register(selector,
                SelectionKey.OP_WRITE | SelectionKey.OP_READ);
        outgoingConnection.setSelectionKey(channelKey);
        channelKey.attach(outgoingConnection);

    } catch (IOException ioe) {
        outgoingConnection.reportConnectionProblem(ioe);
    }
}

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

/**
 * /* w  w w.ja va  2 s .c  o m*/
 */
@Override
void doAccept(SelectionKey selectionKey) throws IOException {
    ServerSocketChannel serverChannel = (ServerSocketChannel) selectionKey.channel();
    SocketChannel channel = serverChannel.accept();

    if (this.expectedClientContainersMonitor.getCount() == 0) {
        logger.warn("Refusing connection from " + channel.getRemoteAddress() + ", since "
                + this.expectedClientContainers + " ApplicationContainerClients "
                + "identified by 'expectedClientContainers' already connected.");
        this.closeChannel(channel);
    } else {
        channel.configureBlocking(false);
        SelectionKey clientSelectionKey = channel.register(this.selector, SelectionKey.OP_READ);
        if (logger.isInfoEnabled()) {
            logger.info("Accepted conection request from: " + channel.socket().getRemoteSocketAddress());
        }
        if (this.masterSelectionKey != null) {
            this.containerDelegates.put(clientSelectionKey,
                    new ContainerDelegateImpl(clientSelectionKey, this));
        } else {
            this.masterSelectionKey = clientSelectionKey;
            this.masterSelectionKey.attach(true);
        }
        this.expectedClientContainersMonitor.countDown();
    }
}

From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkServer.java

/**
 * ?, ?Session, ?Session, /*from  w  ww  .  ja v a  2  s.co m*/
 * Session?
 * @param key
 * @throws IOException
 */
private void onAccept(SelectionKey key) throws IOException {
    SocketChannel channel = ((ServerSocketChannel) key.channel()).accept();
    opsChangeRequstMap.put(channel, new SocketChannelOPSChangeRequest(channel, 0));
    if (logger.isWarnEnabled())
        logger.warn("Accept client from : " + channel.socket().getRemoteSocketAddress());
    channel.configureBlocking(false);
    Session session = sessionManager.newSession(this, channel, false);
    channel.register(selector, SelectionKey.OP_READ, session);
    session.start();
}

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

/**
 * Run the I/O dispatcher.//  w  w  w. java 2  s.  c  o m
 * This method contains the event loop that polls the selector, reads the incoming
 * packets and dispatches the work.
 * It only returns when {@link #stop()} is called.
 */
public void run() {
    while (true) {
        try {
            selector.select();
        } catch (IOException ex) {
            log.error("Exception in select; I/O dispatcher will be shut down", ex);
            return;
        }
        // Execute pending selector operations
        while (true) {
            SelectorOperation request = selectorOperationQueue.poll();
            if (request == null) {
                break;
            }
            request.execute(selector);
            if (!selector.isOpen()) {
                return;
            }
        }
        for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext();) {
            SelectionKey key = it.next();
            it.remove();
            if (key.isValid() && key.isReadable()) {
                receive((Endpoint) key.attachment(), (DatagramChannel) key.channel());
            }
        }
    }
}

From source file:org.cloudata.core.commitlog.WorkerPool.java

private void handleWrite(SelectionKey key) {
    Pipe pipe = (Pipe) key.attachment();

    try {//  w w w  .  j  a v  a 2 s . c  o m
        pipe.write(key.channel());
    } catch (CommitLogShutDownException e) {
        workerPool.shutdown();
    } catch (Exception e) {
        LOG.error("error in handling write due to : ", e);
        cleanupErrorPipe(pipe);
    }
}

From source file:org.cloudata.core.commitlog.WorkerPool.java

private void handleConnection(SelectionKey key) {
    Pipe pipe = (Pipe) key.attachment();

    try {//from  ww w.  ja  v a  2  s  . c o m
        pipe.connect(key.channel());
    } catch (CommitLogShutDownException e) {
        workerPool.shutdown();
    } catch (Exception e) {
        LOG.error("error in handling connection due to : ", e);
        cleanupErrorPipe(pipe);
    }
}

From source file:org.cloudata.core.commitlog.WorkerPool.java

private void handleData(SelectionKey key) {
    Pipe pipe = (Pipe) key.attachment();

    try {/*from w ww .  ja  v a2 s .  c  om*/
        pipe.read(key.channel());
    } catch (CommitLogShutDownException e) {
        workerPool.shutdown();
    } catch (Exception e) {
        if (e instanceof PipeNormallyClosed) {
            pipeSet.remove(pipe);
            pipe.close();
            LOG.debug("Pipe#" + pipe.getPipeKey() + " is gracefully closed.");
        } else {
            LOG.error("error in reading data due to ", e);
            cleanupErrorPipe(pipe);
        }
    }
}

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

@Override
public void run() {
    final ByteBuffer buffer = bufferPool.poll();
    while (!stopped) {
        try {//from w  w w  . ja  v a 2  s  .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;
                    }
                    DatagramChannel channel = (DatagramChannel) key.channel();
                    SocketAddress socketAddress;
                    buffer.clear();
                    while (!stopped && (socketAddress = channel.receive(buffer)) != null) {
                        String sender = "";
                        if (socketAddress instanceof InetSocketAddress) {
                            sender = ((InetSocketAddress) socketAddress).getAddress().toString();
                        }

                        // create a byte array from the buffer
                        buffer.flip();
                        byte bytes[] = new byte[buffer.limit()];
                        buffer.get(bytes, 0, buffer.limit());

                        final Map<String, String> metadata = EventFactoryUtil.createMapWithSender(sender);
                        final E event = eventFactory.create(bytes, metadata, null);
                        events.offer(event);

                        buffer.clear();
                    }
                }
            }
        } catch (InterruptedException e) {
            stopped = true;
            Thread.currentThread().interrupt();
        } catch (IOException e) {
            logger.error("Error reading from DatagramChannel", e);
        }
    }

    if (buffer != null) {
        try {
            bufferPool.put(buffer);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}