Search in sources :

Example 21 with SelectionKey

use of java.nio.channels.SelectionKey in project Mycat-Server by MyCATApache.

the class NIOSocketWR method clearSelectionKey.

private void clearSelectionKey() {
    try {
        SelectionKey key = this.processKey;
        if (key != null && key.isValid()) {
            key.attach(null);
            key.cancel();
        }
    } catch (Exception e) {
        AbstractConnection.LOGGER.warn("clear selector keys err:" + e);
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) IOException(java.io.IOException)

Example 22 with SelectionKey

use of java.nio.channels.SelectionKey in project cobar by alibaba.

the class AbstractConnection method enableWrite.

/**
     * 打开写事件
     */
private void enableWrite() {
    final Lock lock = this.keyLock;
    lock.lock();
    try {
        SelectionKey key = this.processKey;
        key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
    } finally {
        lock.unlock();
    }
    processKey.selector().wakeup();
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock)

Example 23 with SelectionKey

use of java.nio.channels.SelectionKey in project cobar by alibaba.

the class AbstractConnection method disableRead.

/**
     * 关闭读事件
     */
public void disableRead() {
    final Lock lock = this.keyLock;
    lock.lock();
    try {
        SelectionKey key = this.processKey;
        key.interestOps(key.interestOps() & OP_NOT_READ);
    } finally {
        lock.unlock();
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock)

Example 24 with SelectionKey

use of java.nio.channels.SelectionKey in project http-kit by http-kit.

the class HttpClient method run.

public void run() {
    while (running) {
        try {
            Request first = requests.peek();
            long timeout = 2000;
            if (first != null) {
                timeout = Math.max(first.toTimeout(currentTimeMillis()), 200L);
            }
            int select = selector.select(timeout);
            long now = currentTimeMillis();
            if (select > 0) {
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> ite = selectedKeys.iterator();
                while (ite.hasNext()) {
                    SelectionKey key = ite.next();
                    if (!key.isValid()) {
                        continue;
                    }
                    if (key.isConnectable()) {
                        finishConnect(key, now);
                    } else if (key.isReadable()) {
                        doRead(key, now);
                    } else if (key.isWritable()) {
                        doWrite(key);
                    }
                    ite.remove();
                }
            }
            clearTimeout(now);
            processPending();
        } catch (Throwable e) {
            // catch any exception (including OOM), print it: do not exits the loop
            HttpUtils.printError("select exception, should not happen", e);
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey)

Example 25 with SelectionKey

use of java.nio.channels.SelectionKey in project http-kit by http-kit.

the class NBlockingSSL method main.

public static void main(String[] args) throws IOException {
    engine = CLIENT_CONTEXT.createSSLEngine();
    engine.setUseClientMode(true);
    selector = Selector.open();
    socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    key = socketChannel.register(selector, SelectionKey.OP_CONNECT);
    socketChannel.connect(new InetSocketAddress(HOST, 443));
    int i = 0;
    // peerNetData.clear();
    while (true) {
        int select = selector.select(1000);
        if (select > 0) {
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            final Iterator<SelectionKey> ite = selectionKeys.iterator();
            while (ite.hasNext()) {
                final SelectionKey key = ite.next();
                if (key.isConnectable()) {
                    if (socketChannel.finishConnect()) {
                        key.interestOps(SelectionKey.OP_WRITE);
                        engine.beginHandshake();
                    }
                } else if (key.isReadable()) {
                    if (!isHandshakeDone) {
                        doHandshake();
                    } else {
                        int read = socketChannel.read(peerNetData);
                        if (read > 0) {
                            peerNetData.flip();
                            SSLEngineResult res = engine.unwrap(peerNetData, peerAppData);
                            if (res.getStatus() == SSLEngineResult.Status.OK) {
                                peerAppData.flip();
                                byte[] data = new byte[peerAppData.remaining()];
                                peerAppData.get(data);
                                i++;
                                logger.info("get data length: " + new String(data).length());
                                key.interestOps(SelectionKey.OP_WRITE);
                                peerAppData.clear();
                                if (i > 5) {
                                    return;
                                }
                            // peerNetData.clear();
                            }
                            logger.info("read unwrap, " + res);
                            peerNetData.compact();
                        }
                    }
                } else if (key.isWritable()) {
                    if (!isHandshakeDone) {
                        doHandshake();
                    } else {
                        myNetData.clear();
                        ByteBuffer buffer = ByteBuffer.wrap(("GET / HTTP/1.1\r\nHost: " + HOST + "\r\n\r\n").getBytes());
                        SSLEngineResult res = engine.wrap(buffer, myNetData);
                        if (res.getStatus() == Status.OK) {
                            myNetData.flip();
                            socketChannel.write(myNetData);
                            if (!myNetData.hasRemaining()) {
                                key.interestOps(SelectionKey.OP_READ);
                            }
                        }
                    }
                }
                ite.remove();
            }
        } else {
            logger.info("waiting");
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) SSLEngineResult(javax.net.ssl.SSLEngineResult) InetSocketAddress(java.net.InetSocketAddress) ByteBuffer(java.nio.ByteBuffer) MappedByteBuffer(java.nio.MappedByteBuffer)

Aggregations

SelectionKey (java.nio.channels.SelectionKey)190 IOException (java.io.IOException)87 SocketChannel (java.nio.channels.SocketChannel)56 Selector (java.nio.channels.Selector)42 ServerSocketChannel (java.nio.channels.ServerSocketChannel)39 ClosedChannelException (java.nio.channels.ClosedChannelException)30 InetSocketAddress (java.net.InetSocketAddress)26 CancelledKeyException (java.nio.channels.CancelledKeyException)25 ByteBuffer (java.nio.ByteBuffer)23 ClosedSelectorException (java.nio.channels.ClosedSelectorException)17 SelectableChannel (java.nio.channels.SelectableChannel)13 Test (org.junit.Test)13 Iterator (java.util.Iterator)9 Socket (java.net.Socket)7 ArrayList (java.util.ArrayList)7 SocketTimeoutException (java.net.SocketTimeoutException)6 AbstractSelectionKey (java.nio.channels.spi.AbstractSelectionKey)6 EOFException (java.io.EOFException)5 DatagramChannel (java.nio.channels.DatagramChannel)5 HashSet (java.util.HashSet)5