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:net.ymate.platform.serv.nio.support.NioSession.java

public void write() throws IOException {
    synchronized (__writeBufferQueue) {
        while (true) {
            ByteBuffer _buffer = __writeBufferQueue.peek();
            if (_buffer == null) {
                __selectionKey.interestOps(SelectionKey.OP_READ);
                break;
            } else {
                int _wLen = __doChannelWrite(_buffer);
                if (_wLen == 0 && _buffer.remaining() > 0) {
                    break;
                }//from  w  w  w. j a v a2 s.  co m
                if (_buffer.remaining() == 0) {
                    __writeBufferQueue.remove();
                } else {
                    break;
                }
            }
        }
    }
}

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 {//w  w  w.ja v a  2  s  .  c om
        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:org.pvalsecc.comm.MultiplexedServer.java

private void createNewClientConnection(SelectionKey key) {
    SocketChannel socket = null;/*from ww w . ja va  2  s . c om*/
    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.commoncrawl.rpc.thriftrpc.ThriftRPCServerChannel.java

@Override
public void Accepted(NIOClientSocket theSocket) throws IOException {
    SelectionKey clientKey = null;
    TNonblockingTransport client = null;
    try {//from  ww w  .  j ava2  s .c  o  m
        // accept the connection
        client = new TNonblockingSocket((SocketChannel) theSocket.getChannel());
        try {
            clientKey = client.registerSelector(eventLoop.getSelector().getSelector(), SelectionKey.OP_READ);
        } catch (IOException e) {
            LOG.error(CCStringUtils.stringifyException(e));
            throw new TTransportException(e);
        }

        // add this key to the map
        ThriftRPCClientChannel frameBuffer = new ThriftRPCClientChannel(this, this, client, clientKey);
        clientKey.attach(frameBuffer);
    } catch (TTransportException tte) {
        // something went wrong accepting.
        LOG.warn("Exception trying to accept!", tte);
        tte.printStackTrace();
        if (clientKey != null)
            cleanupSelectionkey(clientKey);
        if (client != null)
            client.close();
    }
}

From source file:voldemort.server.niosocket.AsyncRequestHandler.java

@Override
protected void write(SelectionKey selectionKey) throws IOException {
    if (outputStream.getBuffer().hasRemaining()) {
        // If we have data, write what we can now...
        try {//  www .  j a  v  a  2 s  .c o m
            int count = socketChannel.write(outputStream.getBuffer());

            if (logger.isTraceEnabled())
                logger.trace("Wrote " + count + " bytes, remaining: " + outputStream.getBuffer().remaining()
                        + " for " + socketChannel.socket());
        } catch (IOException e) {
            if (streamRequestHandler != null) {
                streamRequestHandler.close(new DataOutputStream(outputStream));
                streamRequestHandler = null;
            }

            throw e;
        }

    } else {
        if (logger.isTraceEnabled())
            logger.trace("Wrote no bytes for " + socketChannel.socket());
    }

    // If there's more to write but we didn't write it, we'll take that to
    // mean that we're done here. We don't clear or reset anything. We leave
    // our buffer state where it is and try our luck next time.
    if (outputStream.getBuffer().hasRemaining())
        return;

    // If we don't have anything else to write, that means we're done with
    // the request! So clear the buffers (resizing if necessary).
    if (outputStream.getBuffer().capacity() >= resizeThreshold)
        outputStream.setBuffer(ByteBuffer.allocate(socketBufferSize));
    else
        outputStream.getBuffer().clear();

    if (streamRequestHandler != null && streamRequestHandler.getDirection() == StreamRequestDirection.WRITING) {
        // In the case of streaming writes, it's possible we can process
        // another segment of the stream. We process streaming writes this
        // way because there won't be any other notification for us to do
        // work as we won't be notified via reads.
        if (logger.isTraceEnabled())
            logger.trace("Request is streaming for " + socketChannel.socket());

        handleStreamRequest(selectionKey);
    } else {
        // If we're not streaming writes, signal the Selector that we're
        // ready to read the next request.
        selectionKey.interestOps(SelectionKey.OP_READ);
    }
}

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

public void notifySend(SocketChannel socketChannel) {
    try {//from www .j  a va  2 s.  co  m
        // we synchronize this to make sure we register the key before the selector gets back to sleep again.
        if (socketChannel.isOpen() && selector.isOpen()) {
            selector.wakeup();
            socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);

        }

    } catch (ClosedChannelException e) {
        //Disconnect detected
    } catch (CancelledKeyException e) {

    } catch (Exception e) {

        LoggerFactory.getLogger(this.getClass()).error("Exception", e);

    }
}

From source file:HttpDownloadManager.java

public void run() {
    log.info("HttpDownloadManager thread starting.");

    // The download thread runs until release() is called
    while (!released) {
        // The thread blocks here waiting for something to happen
        try {/* ww  w.ja v a  2s .c  om*/
            selector.select();
        } catch (IOException e) {
            // This should never happen.
            log.log(Level.SEVERE, "Error in select()", e);
            return;
        }

        // If release() was called, the thread should exit.
        if (released)
            break;

        // If any new Download objects are pending, deal with them first
        if (!pendingDownloads.isEmpty()) {
            // Although pendingDownloads is a synchronized list, we still
            // need to use a synchronized block to iterate through its
            // elements to prevent a concurrent call to download().
            synchronized (pendingDownloads) {
                Iterator iter = pendingDownloads.iterator();
                while (iter.hasNext()) {
                    // Get the pending download object from the list
                    DownloadImpl download = (DownloadImpl) iter.next();
                    iter.remove(); // And remove it.

                    // Now begin an asynchronous connection to the
                    // specified host and port. We don't block while
                    // waiting to connect.
                    SelectionKey key = null;
                    SocketChannel channel = null;
                    try {
                        // Open an unconnected channel
                        channel = SocketChannel.open();
                        // Put it in non-blocking mode
                        channel.configureBlocking(false);
                        // Register it with the selector, specifying that
                        // we want to know when it is ready to connect
                        // and when it is ready to read.
                        key = channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT,
                                download);
                        // Create the web server address
                        SocketAddress address = new InetSocketAddress(download.host, download.port);
                        // Ask the channel to start connecting
                        // Note that we don't send the HTTP request yet.
                        // We'll do that when the connection completes.
                        channel.connect(address);
                    } catch (Exception e) {
                        handleError(download, channel, key, e);
                    }
                }
            }
        }

        // Now get the set of keys that are ready for connecting or reading
        Set keys = selector.selectedKeys();
        if (keys == null)
            continue; // bug workaround; should not be needed
        // Loop through the keys in the set
        for (Iterator i = keys.iterator(); i.hasNext();) {
            SelectionKey key = (SelectionKey) i.next();
            i.remove(); // Remove the key from the set before handling

            // Get the Download object we attached to the key
            DownloadImpl download = (DownloadImpl) key.attachment();
            // Get the channel associated with the key.
            SocketChannel channel = (SocketChannel) key.channel();

            try {
                if (key.isConnectable()) {
                    // If the channel is ready to connect, complete the
                    // connection and then send the HTTP GET request to it.
                    if (channel.finishConnect()) {
                        download.status = Status.CONNECTED;
                        // This is the HTTP request we wend
                        String request = "GET " + download.path + " HTTP/1.1\r\n" + "Host: " + download.host
                                + "\r\n" + "Connection: close\r\n" + "\r\n";
                        // Wrap in a CharBuffer and encode to a ByteBuffer
                        ByteBuffer requestBytes = LATIN1.encode(CharBuffer.wrap(request));
                        // Send the request to the server. If the bytes
                        // aren't all written in one call, we busy loop!
                        while (requestBytes.hasRemaining())
                            channel.write(requestBytes);

                        log.info("Sent HTTP request: " + download.host + ":" + download.port + ": " + request);
                    }
                }
                if (key.isReadable()) {
                    // If the key indicates that there is data to be read,
                    // then read it and store it in the Download object.
                    int numbytes = channel.read(buffer);

                    // If we read some bytes, store them, otherwise
                    // the download is complete and we need to note this
                    if (numbytes != -1) {
                        buffer.flip(); // Prepare to drain the buffer
                        download.addData(buffer); // Store the data
                        buffer.clear(); // Prepare for another read
                        log.info("Read " + numbytes + " bytes from " + download.host + ":" + download.port);
                    } else {
                        // If there are no more bytes to read
                        key.cancel(); // We're done with the key
                        channel.close(); // And with the channel.
                        download.status = Status.DONE;
                        if (download.listener != null) // notify listener
                            download.listener.done(download);
                        log.info("Download complete from " + download.host + ":" + download.port);
                    }
                }
            } catch (Exception e) {
                handleError(download, channel, key, e);
            }
        }
    }
    log.info("HttpDownloadManager thread exiting.");
}

From source file:edu.tsinghua.lumaqq.qq.net.TCPPort.java

public void processConnect(SelectionKey sk) throws IOException {
    //?SocketChannel
    channel.finishConnect();//from  www  .j  a  v  a2 s.co  m
    while (!channel.isConnected()) {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            // ??
        }
        channel.finishConnect();
    }
    sk.interestOps(SelectionKey.OP_READ);
    log.debug("QQ?");
}

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

private void doRead(SelectionKey key) {

    final IncomingConnection incomingConnection = (IncomingConnection) key.attachment();
    try {/*from  www . j  a v  a2 s.  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:edu.tsinghua.lumaqq.qq.net.UDPSocks5Port.java

public void proxyReady(InetSocketAddress bindAddress) throws IOException {
    ready = true;/*  w w  w. j a  va 2  s.co m*/
    // Socks Serverbind address
    channel.connect(bindAddress);
    ((PortGate) getPool()).getPorter().register(this, SelectionKey.OP_READ);
}