Example usage for java.nio.channels SelectionKey OP_CONNECT

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

Introduction

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

Prototype

int OP_CONNECT

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

Click Source Link

Document

Operation-set bit for socket-connect operations.

Usage

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

private void finishConnection(SelectionKey key) {
    try {/*from w w w .j  a va2s  . c om*/
        ((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:com.buaa.cfs.net.SocketIOWithTimeout.java

private static String timeoutExceptionString(SelectableChannel channel, long timeout, int ops) {

    String waitingFor;/*from w ww .  ja v a  2  s  . c  o m*/
    switch (ops) {

    case SelectionKey.OP_READ:
        waitingFor = "read";
        break;

    case SelectionKey.OP_WRITE:
        waitingFor = "write";
        break;

    case SelectionKey.OP_CONNECT:
        waitingFor = "connect";
        break;

    default:
        waitingFor = "" + ops;
    }

    return timeout + " millis timeout while " + "waiting for channel to be ready for " + waitingFor + ". ch : "
            + channel;
}

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 {//from  w ww . j  av  a 2  s.com
            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:com.facebook.infrastructure.net.TcpConnection.java

public void connect(SelectionKey key) {
    key.interestOps(key.interestOps() & (~SelectionKey.OP_CONNECT));
    try {//from   w  w w. java2s  .  co m
        if (!socketChannel_.finishConnect()) {
            throw new IOException("Unable to finishConnect to " + socketChannel_);
        }
        SelectorManager.getSelectorManager().modifyKeyForRead(key);
        connected_.set(true);

        // this will flush the pending
        if (!pendingWrites_.isEmpty()) {
            SelectorManager.getSelectorManager().modifyKeyForWrite(key_);
        }
        resumeStreaming();
    } catch (IOException e) {
        logger_.error("Encountered IOException on connection: " + socketChannel_, e);
        errorClose();
    }
}

From source file:com.taobao.gecko.core.nio.impl.Reactor.java

final void dispatchEvent(final Set<SelectionKey> selectedKeySet) {
    final Iterator<SelectionKey> it = selectedKeySet.iterator();
    boolean skipOpRead = false; // 
    while (it.hasNext()) {
        final SelectionKey key = it.next();
        it.remove();/*from   w w w.j  a va2  s .  com*/
        if (!key.isValid()) {
            if (key.attachment() != null) {
                this.controller.closeSelectionKey(key);
            } else {
                key.cancel();
            }
            continue;
        }
        try {
            if (key.isAcceptable()) {
                this.controller.onAccept(key);
                continue;
            }
            if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
                // Remove write interest
                key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
                this.controller.onWrite(key);
                if (!this.controller.isHandleReadWriteConcurrently()) {
                    skipOpRead = true;
                }
            }
            if (!skipOpRead && (key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
                // read
                key.interestOps(key.interestOps() & ~SelectionKey.OP_READ);
                // 
                if (!this.controller.getStatistics().isReceiveOverFlow()) {
                    // Remove read interest

                    this.controller.onRead(key);// 
                    continue;
                } else {
                    key.interestOps(key.interestOps() // 
                            | SelectionKey.OP_READ);
                }

            }
            if ((key.readyOps() & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT) {
                this.controller.onConnect(key);
                continue;
            }

        } catch (final RejectedExecutionException e) {
            // 
            if (key.attachment() instanceof AbstractNioSession) {
                ((AbstractSession) key.attachment()).onException(e);
            }
            this.controller.notifyException(e);
            if (this.selector.isOpen()) {
                continue;
            } else {
                break;
            }
        } catch (final CancelledKeyException e) {
            // ignore
        } catch (final Exception e) {
            if (key.attachment() instanceof AbstractNioSession) {
                ((AbstractSession) key.attachment()).onException(e);
            }
            this.controller.closeSelectionKey(key);
            this.controller.notifyException(e);
            log.error("Reactor dispatch events error", e);
            if (this.selector.isOpen()) {
                continue;
            } else {
                break;
            }
        }
    }
}

From source file:com.alibaba.napoli.gecko.core.nio.impl.Reactor.java

final void dispatchEvent(final Set<SelectionKey> selectedKeySet) {
    final Iterator<SelectionKey> it = selectedKeySet.iterator();
    boolean skipOpRead = false; // ?
    while (it.hasNext()) {
        final SelectionKey key = it.next();
        it.remove();// w w  w.j  av a2 s. co  m
        if (!key.isValid()) {
            if (key.attachment() != null) {
                this.controller.closeSelectionKey(key);
            } else {
                key.cancel();
            }
            continue;
        }
        try {
            if (key.isAcceptable()) {
                this.controller.onAccept(key);
                continue;
            }
            if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
                // Remove write interest
                key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
                this.controller.onWrite(key);
                if (!this.controller.isHandleReadWriteConcurrently()) {
                    skipOpRead = true;
                }
            }
            if (!skipOpRead && (key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
                // read
                key.interestOps(key.interestOps() & ~SelectionKey.OP_READ);
                // ???
                if (!this.controller.getStatistics().isReceiveOverFlow()) {
                    // Remove read interest

                    this.controller.onRead(key);// ?
                    continue;
                } else {
                    key.interestOps(key.interestOps() // 
                            | SelectionKey.OP_READ);
                }

            }
            if ((key.readyOps() & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT) {
                this.controller.onConnect(key);
                continue;
            }

        } catch (final RejectedExecutionException e) {
            // ???
            if (key.attachment() instanceof AbstractNioSession) {
                ((AbstractSession) key.attachment()).onException(e);
            }
            this.controller.notifyException(e);
            if (this.selector.isOpen()) {
                continue;
            } else {
                break;
            }
        } catch (final CancelledKeyException e) {
            // ignore
        } catch (final Exception e) {
            if (key.attachment() instanceof AbstractNioSession) {
                ((AbstractSession) key.attachment()).onException(e);
            }
            this.controller.closeSelectionKey(key);
            this.controller.notifyException(e);
            log.error("Reactor dispatch events error", e);
            if (this.selector.isOpen()) {
                continue;
            } else {
                break;
            }
        }
    }
}

From source file:Proxy.java

String printSelectionOps(SelectionKey key) {
    StringBuilder sb = new StringBuilder();
    if ((key.readyOps() & SelectionKey.OP_ACCEPT) != 0)
        sb.append("OP_ACCEPT ");
    if ((key.readyOps() & SelectionKey.OP_CONNECT) != 0)
        sb.append("OP_CONNECT ");
    if ((key.readyOps() & SelectionKey.OP_READ) != 0)
        sb.append("OP_READ ");
    if ((key.readyOps() & SelectionKey.OP_WRITE) != 0)
        sb.append("OP_WRITE ");
    return sb.toString();
}

From source file:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpMultiplexer.java

protected void updateConnectInterest(NIOClientSocketHandler clientHandler, Selector selector) {
    SocketChannel socketChannel = clientHandler.getSocketChannel();
    if (!socketChannel.isOpen())
        return;//from   w  w  w .j  av a  2  s.  c  om

    // We are interested in connect if not already done
    if (!socketChannel.isConnected())
        addInterest(socketChannel, SelectionKey.OP_CONNECT, clientHandler, selector);
    else
        removeInterest(socketChannel, SelectionKey.OP_CONNECT, selector);
}

From source file:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpMultiplexer.java

protected boolean finalizeConnect(NIOClientSocketHandler clientHandler, SocketChannel channel,
        Selector selector) {/*from  w w  w . ja v a 2 s  . c om*/
    try {
        // Finish the connection handshake
        channel.finishConnect();

        log.debug("[" + clientHandler.getId() + "] Connected to " + channel.socket().getInetAddress());

        // Unregister connect interest
        removeInterest(channel, SelectionKey.OP_CONNECT, selector);

        return true;
    } catch (SocketException e) {
        log.error("[" + clientHandler.getId() + "] Could not connect to remote server : " + e.getMessage());
        return false;
    } catch (Exception e) {
        log.error("[" + clientHandler.getId() + "] Could not finalize connection", e);
        return false;
    }
}

From source file:net.ymate.platform.serv.nio.support.NioEventGroup.java

protected void __doRegisterEvent() throws IOException {
    if (isServer()) {
        processor().registerEvent(__channel, SelectionKey.OP_ACCEPT, null);
    } else {/* w ww . j a  v  a  2 s.  c  o m*/
        processor().registerEvent(__channel, SelectionKey.OP_CONNECT, session());
        if (connectionTimeout() > 0) {
            session().connectSync(connectionTimeout());
        }
    }
}