Example usage for java.nio.channels SelectionKey OP_READ

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

Introduction

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

Prototype

int OP_READ

To view the source code for java.nio.channels SelectionKey OP_READ.

Click Source Link

Document

Operation-set bit for read operations.

Usage

From source file:org.commoncrawl.io.internal.NIOSocketSelector.java

/** register a socket for READ events */
public void registerForRead(NIOClientSocket theSocket) throws IOException {
    registerSocket(theSocket, SelectionKey.OP_READ);
}

From source file:com.ok2c.lightmtp.impl.protocol.SimpleSendEnvelopCodec.java

@Override
public void produceData(final IOSession iosession, final ClientState sessionState)
        throws IOException, SMTPProtocolException {
    Args.notNull(iosession, "IO session");
    Args.notNull(sessionState, "Session state");
    if (sessionState.getRequest() == null) {
        if (sessionState.isTerminated()) {
            this.codecState = CodecState.COMPLETED;
        }/*ww w.  j  a  v a2  s. com*/
        return;
    }

    SessionOutputBuffer buf = this.iobuffers.getOutbuf();
    DeliveryRequest request = sessionState.getRequest();

    switch (this.codecState) {
    case MAIL_REQUEST_READY:
        SMTPCommand mailFrom = new SMTPCommand("MAIL", "FROM:<" + request.getSender() + ">");
        this.writer.write(mailFrom, buf);

        this.codecState = CodecState.MAIL_RESPONSE_EXPECTED;
        iosession.setEvent(SelectionKey.OP_READ);
        break;
    case RCPT_REQUEST_READY:
        String recipient = this.recipients.getFirst();

        SMTPCommand rcptTo = new SMTPCommand("RCPT", "TO:<" + recipient + ">");
        this.writer.write(rcptTo, buf);

        this.codecState = CodecState.RCPT_RESPONSE_EXPECTED;
        break;
    case DATA_REQUEST_READY:
        SMTPCommand data = new SMTPCommand("DATA");
        this.writer.write(data, buf);
        this.codecState = CodecState.DATA_RESPONSE_EXPECTED;
        break;
    }

    if (buf.hasData()) {
        buf.flush(iosession.channel());
    }
    if (!buf.hasData()) {
        iosession.clearEvent(SelectionKey.OP_WRITE);
    }
}

From source file:com.facebook.infrastructure.net.TcpConnection.java

private void setupChannel() throws IOException {
    socketChannel_ = SocketChannel.open();
    socketChannel_.configureBlocking(false);
    logger_.info("Opening socketchannel to " + remoteEp_.getInetAddress() + "(" + socketChannel_ + ")");
    if (!socketChannel_.connect(remoteEp_.getInetAddress())) {
        key_ = SelectorManager.getSelectorManager().register(socketChannel_, this, SelectionKey.OP_CONNECT);
    } else {//from   w w w. j  a va  2 s  .  c  o  m
        key_ = SelectorManager.getSelectorManager().register(socketChannel_, this, SelectionKey.OP_READ);
        connected_.set(true);
    }
}

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  .jav  a2s.  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:org.reunionemu.jreunion.server.Network.java

@Override
public void run() {
    logger.info("network thread starting");
    while (true) {
        try {//  w  ww .jav a 2 s.  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);
        }
    }

}

From source file:org.commoncrawl.io.internal.NIOSocketSelector.java

/** register a socket for READ AND WRITE events */
public void registerForReadAndWrite(NIOClientSocket theSocket) throws IOException {
    registerSocket(theSocket, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}

From source file:com.facebook.infrastructure.net.UdpConnection.java

public void read(SelectionKey key) {
    key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
    ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
    try {/*from   ww  w  .  ja  v  a 2  s  .c o  m*/
        SocketAddress sa = socketChannel_.receive(buffer);
        if (sa == null) {
            logger_.debug("*** No datagram packet was available to be read ***");
            return;
        }
        buffer.flip();

        byte[] bytes = gobbleHeaderAndExtractBody(buffer);
        if (bytes.length > 0) {
            DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
            Message message = Message.serializer().deserialize(dis);
            if (message != null) {
                MessagingService.receive(message);
            }
        }
    } catch (IOException ioe) {
        logger_.warn(LogUtil.throwableToString(ioe));
    } finally {
        key.interestOps(key_.interestOps() | SelectionKey.OP_READ);
    }
}

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);
                }//  w  w w .j av  a  2s .  c o m
            }
        }

        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:edu.tsinghua.lumaqq.qq.net.Porter.java

/**
 * ???//from  www.jav a2  s .  c o  m
 * 
 * @param proxy
 *       IProxy
 * @throws ClosedChannelException
 *       
 */
public void register(IProxy proxy) throws ClosedChannelException {
    SelectableChannel channel = proxy.channel();
    if (channel instanceof SocketChannel)
        channel.register(selector, SelectionKey.OP_CONNECT, proxy.getNIOHandler());
    else if (channel instanceof DatagramChannel)
        channel.register(selector, SelectionKey.OP_READ, proxy.getNIOHandler());
    if (!proxies.contains(proxy))
        proxies.add(proxy);
}

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

private static String describeInterestOps(int interestOps) {
    final TreeSet<String> result = new TreeSet<String>();
    if ((interestOps & SelectionKey.OP_ACCEPT) != 0)
        result.add("ACCEPT");
    if ((interestOps & SelectionKey.OP_CONNECT) != 0)
        result.add("CONNECT");
    if ((interestOps & SelectionKey.OP_READ) != 0)
        result.add("READ");
    if ((interestOps & SelectionKey.OP_WRITE) != 0)
        result.add("WRITE");
    return StringUtils.join(result, "|");
}