Search in sources :

Example 76 with SelectionKey

use of java.nio.channels.SelectionKey in project jeromq by zeromq.

the class Poller method run.

@Override
public void run() {
    int returnsImmediately = 0;
    while (!stopping) {
        //  Execute any due timers.
        long timeout = executeTimers();
        while (retired.compareAndSet(true, false)) {
            Iterator<Map.Entry<SelectableChannel, PollSet>> it = fdTable.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<SelectableChannel, PollSet> entry = it.next();
                SelectableChannel ch = entry.getKey();
                PollSet pollset = entry.getValue();
                if (pollset.key == null) {
                    try {
                        pollset.key = ch.register(selector, pollset.ops, pollset.handler);
                    } catch (ClosedChannelException e) {
                    }
                }
                if (pollset.cancelled || !ch.isOpen()) {
                    if (pollset.key != null) {
                        pollset.key.cancel();
                    }
                    it.remove();
                }
            }
        }
        //  Wait for events.
        int rc;
        long start = System.currentTimeMillis();
        try {
            rc = selector.select(timeout);
        } catch (IOException e) {
            throw new ZError.IOException(e);
        }
        if (rc == 0) {
            //  Guess JDK epoll bug
            if (timeout == 0 || System.currentTimeMillis() - start < timeout / 2) {
                returnsImmediately++;
            } else {
                returnsImmediately = 0;
            }
            if (returnsImmediately > 10) {
                rebuildSelector();
                returnsImmediately = 0;
            }
            continue;
        }
        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey key = it.next();
            IPollEvents evt = (IPollEvents) key.attachment();
            it.remove();
            try {
                if (key.isReadable()) {
                    evt.inEvent();
                } else if (key.isAcceptable()) {
                    evt.acceptEvent();
                } else if (key.isConnectable()) {
                    evt.connectEvent();
                }
                if (key.isWritable()) {
                    evt.outEvent();
                }
            } catch (CancelledKeyException e) {
            // channel might have been closed
            }
        }
    }
    stopped = true;
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) SelectionKey(java.nio.channels.SelectionKey) CancelledKeyException(java.nio.channels.CancelledKeyException) IOException(java.io.IOException) SelectableChannel(java.nio.channels.SelectableChannel) Map(java.util.Map) HashMap(java.util.HashMap)

Example 77 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 78 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)

Example 79 with SelectionKey

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

the class HttpServer method accept.

void accept(SelectionKey key) {
    ServerSocketChannel ch = (ServerSocketChannel) key.channel();
    SocketChannel s;
    try {
        while ((s = ch.accept()) != null) {
            s.configureBlocking(false);
            HttpAtta atta = new HttpAtta(maxBody, maxLine, proxyProtocolOption);
            SelectionKey k = s.register(selector, OP_READ, atta);
            atta.channel = new AsyncChannel(k, this);
        }
    } catch (Exception e) {
        // eg: too many open files. do not quit
        HttpUtils.printError("accept incoming request", e);
    }
}
Also used : ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) SelectionKey(java.nio.channels.SelectionKey) ServerSocketChannel(java.nio.channels.ServerSocketChannel) LineTooLargeException(org.httpkit.LineTooLargeException) ProtocolException(org.httpkit.ProtocolException) IOException(java.io.IOException) ClosedSelectorException(java.nio.channels.ClosedSelectorException) RequestTooLargeException(org.httpkit.RequestTooLargeException)

Example 80 with SelectionKey

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

the class MakeupIdelConnection method main.

public static void main(String[] args) throws IOException {
    final Selector selector = Selector.open();
    InetSocketAddress[] locals = { new InetSocketAddress("127.0.0.1", 4348) };
    // InetSocketAddress remote = new InetSocketAddress("192.168.1.114",
    // 9090);
    long start = System.currentTimeMillis();
    int connected = 0;
    int currentConnectionPerIP = 0;
    while (true) {
        if (System.currentTimeMillis() - start > 1000 * 60 * 10) {
            break;
        }
        for (int i = 0; i < connectionPerIP / STEPS && currentConnectionPerIP < connectionPerIP; ++i, ++currentConnectionPerIP) {
            for (InetSocketAddress addr : locals) {
                SocketChannel ch = SocketChannel.open();
                ch.configureBlocking(false);
                Socket s = ch.socket();
                s.setReuseAddress(true);
                // s.bind(addr);
                ch.register(selector, SelectionKey.OP_CONNECT);
                ch.connect(addr);
            }
        }
        // 10s
        int select = selector.select(1000 * 10);
        if (select > 0) {
            System.out.println("select return: " + select + " events ; current connection per ip: " + currentConnectionPerIP);
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> it = selectedKeys.iterator();
            while (it.hasNext()) {
                SelectionKey key = it.next();
                if (key.isConnectable()) {
                    SocketChannel ch = (SocketChannel) key.channel();
                    if (ch.finishConnect()) {
                        ++connected;
                        if (connected % (connectionPerIP * locals.length / 10) == 0) {
                            System.out.println("connected: " + connected);
                        }
                        key.interestOps(SelectionKey.OP_READ);
                    }
                }
            }
            selectedKeys.clear();
        }
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) SelectionKey(java.nio.channels.SelectionKey) InetSocketAddress(java.net.InetSocketAddress) Socket(java.net.Socket) Selector(java.nio.channels.Selector)

Aggregations

SelectionKey (java.nio.channels.SelectionKey)202 IOException (java.io.IOException)93 SocketChannel (java.nio.channels.SocketChannel)59 Selector (java.nio.channels.Selector)44 ServerSocketChannel (java.nio.channels.ServerSocketChannel)41 ClosedChannelException (java.nio.channels.ClosedChannelException)30 InetSocketAddress (java.net.InetSocketAddress)27 CancelledKeyException (java.nio.channels.CancelledKeyException)25 ByteBuffer (java.nio.ByteBuffer)24 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