Search in sources :

Example 96 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 97 with SelectionKey

use of java.nio.channels.SelectionKey in project wifikeyboard by IvanVolosyuk.

the class HttpServer method run.

@Override
public void run() {
    //    Debug.d("HttpServer started listening");
    try {
        ch.configureBlocking(false);
        SelectionKey serverkey = ch.register(selector, SelectionKey.OP_ACCEPT);
        final ArrayList<Update> newUpdates = new ArrayList<Update>();
        Action checkUpdates = new Action() {

            @Override
            public Object run() {
                for (Update u : pendingUpdates) {
                    newUpdates.add(u);
                }
                pendingUpdates.clear();
                return null;
            }
        };
        while (true) {
            newUpdates.clear();
            runAction(checkUpdates);
            for (Update u : newUpdates) {
                u.run();
            }
            //        Debug.d("waiting for event");
            selector.select();
            //        Debug.d("got an event");
            Set<SelectionKey> keys = selector.selectedKeys();
            for (Iterator<SelectionKey> i = keys.iterator(); i.hasNext(); ) {
                SelectionKey key = i.next();
                i.remove();
                if (key == serverkey) {
                    if (key.isAcceptable()) {
                        SocketChannel client = ch.accept();
                        //              Debug.d("NEW CONNECTION from " + client.socket().getRemoteSocketAddress());
                        client.configureBlocking(false);
                        SelectionKey clientkey = client.register(selector, SelectionKey.OP_READ);
                        HttpConnection con = newConnection(client);
                        clientkey.attach(con);
                        con.setKey(clientkey);
                    }
                } else {
                    HttpConnection conn = (HttpConnection) key.attachment();
                    try {
                        HttpConnection.ConnectionState prevState, newState;
                        if (key.isReadable()) {
                            prevState = HttpConnection.ConnectionState.SELECTOR_WAIT_FOR_NEW_INPUT;
                            //                Debug.d("processing read event");
                            //                long start = System.currentTimeMillis();
                            newState = conn.newInput();
                        //                long end = System.currentTimeMillis();
                        //                Debug.d("delay = " + (end - start));
                        //                int size = android.os.Debug.getThreadAllocSize();
                        //                android.os.Debug.stopAllocCounting();
                        //                Log.d("wifikeyboard", "finished read event, allocs = " + size);
                        //                android.os.Debug.startAllocCounting();
                        } else if (key.isWritable()) {
                            prevState = HttpConnection.ConnectionState.SELECTOR_WAIT_FOR_OUTPUT_BUFFER;
                            //                Debug.d("processing write event");
                            newState = conn.newOutputBuffer();
                        //                Log.d("wifikeyboard", "finished write event");
                        } else {
                            continue;
                        }
                        if (newState == prevState)
                            continue;
                        key.interestOps((newState == HttpConnection.ConnectionState.SELECTOR_WAIT_FOR_NEW_INPUT ? SelectionKey.OP_READ : 0) | (newState == HttpConnection.ConnectionState.SELECTOR_WAIT_FOR_OUTPUT_BUFFER ? SelectionKey.OP_WRITE : 0));
                    } catch (IOException io) {
                        //                  conn.getClient().socket().getRemoteSocketAddress());
                        if (key != null)
                            key.cancel();
                        conn.getClient().close();
                    } catch (ConnectionFailureException e) {
                        if (key != null)
                            key.cancel();
                        conn.getClient().close();
                    } catch (NumberFormatException e) {
                        // FIXME: move to ConnectionFailureException
                        if (key != null)
                            key.cancel();
                        conn.getClient().close();
                    }
                }
            }
        }
    } catch (IOException e) {
        Debug.e("network loop terminated", e);
    } catch (NetworkThreadStopException e) {
        Debug.e("network thread stop requested", e);
    }
    try {
        selector.close();
    } catch (Throwable t) {
    }
    try {
        ch.close();
    } catch (Throwable t) {
    }
    onExit();
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ConnectionFailureException(com.volosyukivan.HttpConnection.ConnectionFailureException)

Example 98 with SelectionKey

use of java.nio.channels.SelectionKey in project zm-mailbox by Zimbra.

the class ZimbraSocketAcceptor method accept.

@Override
protected NioSession accept(IoProcessor<NioSession> processor, ServerSocketChannel handle) throws Exception {
    SelectionKey key = handle.keyFor(selector);
    if ((key == null) || (!key.isValid()) || (!key.isAcceptable())) {
        return null;
    }
    // accept the connection from the client
    SocketChannel ch = handle.accept();
    if (ch == null) {
        return null;
    }
    return new NioSocketSession(this, processor, ch);
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel)

Example 99 with SelectionKey

use of java.nio.channels.SelectionKey in project zm-mailbox by Zimbra.

the class ZimbraSocketAcceptor method close.

@Override
protected void close(ServerSocketChannel handle) throws Exception {
    SelectionKey key = handle.keyFor(selector);
    if (key != null) {
        key.cancel();
    }
    handle.close();
}
Also used : SelectionKey(java.nio.channels.SelectionKey)

Example 100 with SelectionKey

use of java.nio.channels.SelectionKey in project aerospike-client-java by aerospike.

the class NioEventLoop method runCommands.

private void runCommands() throws Exception {
    registerCommands();
    runScheduled();
    awakened.set(false);
    selector.select(selectorTimeout);
    if (awakened.get()) {
        selector.wakeup();
    }
    final Set<SelectionKey> keys = selector.selectedKeys();
    if (keys.isEmpty()) {
        return;
    }
    try {
        final Iterator<SelectionKey> iter = keys.iterator();
        while (iter.hasNext()) {
            final SelectionKey key = iter.next();
            if (!key.isValid()) {
                continue;
            }
            processKey(key);
        }
    } finally {
        keys.clear();
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey)

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