Search in sources :

Example 61 with SelectionKey

use of java.nio.channels.SelectionKey in project Cloud9 by lintool.

the class VocabServer method run.

public void run() {
    System.err.println("Vocab server running...");
    while (true) {
        try {
            selector.select();
        } catch (IOException e) {
            System.err.println("Caught exception in select()");
            e.printStackTrace();
            break;
        }
        if (selector.isOpen() == false)
            break;
        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey key = it.next();
            try {
                processSelectionKey(key);
            } catch (IOException e) {
                key.cancel();
                System.err.println("Caught exception handling selection key. Key cancelled");
            }
            it.remove();
        }
    }
    System.err.println("Server exiting.");
    System.err.println("  " + (v.size() - 1) + " types processed");
    System.err.println("  " + connections + " connections");
}
Also used : SelectionKey(java.nio.channels.SelectionKey) IOException(java.io.IOException)

Example 62 with SelectionKey

use of java.nio.channels.SelectionKey in project AndroidAsync by koush.

the class AsyncServer method listen.

public AsyncServerSocket listen(final InetAddress host, final int port, final ListenCallback handler) {
    final ObjectHolder<AsyncServerSocket> holder = new ObjectHolder<AsyncServerSocket>();
    run(new Runnable() {

        @Override
        public void run() {
            ServerSocketChannel closeableServer = null;
            ServerSocketChannelWrapper closeableWrapper = null;
            try {
                closeableServer = ServerSocketChannel.open();
                closeableWrapper = new ServerSocketChannelWrapper(closeableServer);
                final ServerSocketChannel server = closeableServer;
                final ServerSocketChannelWrapper wrapper = closeableWrapper;
                InetSocketAddress isa;
                if (host == null)
                    isa = new InetSocketAddress(port);
                else
                    isa = new InetSocketAddress(host, port);
                server.socket().bind(isa);
                final SelectionKey key = wrapper.register(mSelector.getSelector());
                key.attach(handler);
                handler.onListening(holder.held = new AsyncServerSocket() {

                    @Override
                    public int getLocalPort() {
                        return server.socket().getLocalPort();
                    }

                    @Override
                    public void stop() {
                        StreamUtility.closeQuietly(wrapper);
                        try {
                            key.cancel();
                        } catch (Exception e) {
                        }
                    }
                });
            } catch (IOException e) {
                Log.e(LOGTAG, "wtf", e);
                StreamUtility.closeQuietly(closeableWrapper, closeableServer);
                handler.onCompleted(e);
            }
        }
    });
    return holder.held;
}
Also used : SelectionKey(java.nio.channels.SelectionKey) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) ServerSocketChannel(java.nio.channels.ServerSocketChannel) CancelledKeyException(java.nio.channels.CancelledKeyException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException)

Example 63 with SelectionKey

use of java.nio.channels.SelectionKey in project hs4j by killme2008.

the class NioTCPSession method blockingRead.

/**
	 * Blocking read using temp selector
	 * 
	 * @return
	 * @throws ClosedChannelException
	 * @throws IOException
	 */
protected final int blockingRead() throws ClosedChannelException, IOException {
    int n = 0;
    Selector readSelector = SelectorFactory.getSelector();
    SelectionKey tmpKey = null;
    try {
        if (selectableChannel.isOpen()) {
            tmpKey = selectableChannel.register(readSelector, 0);
            tmpKey.interestOps(tmpKey.interestOps() | SelectionKey.OP_READ);
            int code = readSelector.select(500);
            tmpKey.interestOps(tmpKey.interestOps() & ~SelectionKey.OP_READ);
            if (code > 0) {
                do {
                    n = ((ReadableByteChannel) selectableChannel).read(readBuffer.buf());
                    if (log.isDebugEnabled()) {
                        log.debug("use temp selector read " + n + " bytes");
                    }
                } while (n > 0 && readBuffer.hasRemaining());
                readBuffer.flip();
                decode();
                readBuffer.compact();
            }
        }
    } finally {
        if (tmpKey != null) {
            tmpKey.cancel();
            tmpKey = null;
        }
        if (readSelector != null) {
            // Cancel the key.
            readSelector.selectNow();
            SelectorFactory.returnSelector(readSelector);
        }
    }
    return n;
}
Also used : SelectionKey(java.nio.channels.SelectionKey) Selector(java.nio.channels.Selector)

Example 64 with SelectionKey

use of java.nio.channels.SelectionKey in project hs4j by killme2008.

the class Reactor method dispatchEvent.

/**
	 * Dispatch selected event
	 * 
	 * @param selectedKeySet
	 */
public final void dispatchEvent(Set<SelectionKey> selectedKeySet) {
    Iterator<SelectionKey> it = selectedKeySet.iterator();
    boolean skipOpRead = false;
    while (it.hasNext()) {
        SelectionKey key = it.next();
        it.remove();
        if (!key.isValid()) {
            if (key.attachment() != null) {
                controller.closeSelectionKey(key);
            } else {
                key.cancel();
            }
            continue;
        }
        try {
            if (key.isValid() && key.isAcceptable()) {
                controller.onAccept(key);
                continue;
            }
            if (key.isValid() && (key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
                // Remove write interest
                key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
                controller.onWrite(key);
                if (!controller.isHandleReadWriteConcurrently()) {
                    skipOpRead = true;
                }
            }
            if (!skipOpRead && key.isValid() && (key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
                key.interestOps(key.interestOps() & ~SelectionKey.OP_READ);
                if (!controller.getStatistics().isReceiveOverFlow()) {
                    // Remove read interest
                    controller.onRead(key);
                } else {
                    key.interestOps(key.interestOps() | SelectionKey.OP_READ);
                }
            }
            if ((key.readyOps() & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT) {
                controller.onConnect(key);
            }
        } catch (CancelledKeyException e) {
        // ignore
        } catch (RejectedExecutionException e) {
            if (key.attachment() instanceof AbstractNioSession) {
                ((AbstractNioSession) key.attachment()).onException(e);
            }
            controller.notifyException(e);
            if (selector.isOpen()) {
                continue;
            } else {
                break;
            }
        } catch (Exception e) {
            if (key.attachment() instanceof AbstractNioSession) {
                ((AbstractNioSession) key.attachment()).onException(e);
            }
            controller.closeSelectionKey(key);
            controller.notifyException(e);
            log.error("Reactor dispatch events error", e);
            if (selector.isOpen()) {
                continue;
            } else {
                break;
            }
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) CancelledKeyException(java.nio.channels.CancelledKeyException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) CancelledKeyException(java.nio.channels.CancelledKeyException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ClosedSelectorException(java.nio.channels.ClosedSelectorException)

Example 65 with SelectionKey

use of java.nio.channels.SelectionKey in project hs4j by killme2008.

the class Reactor method checkSessionTimeout.

/**
	 * Check session timeout or idle
	 * 
	 * @return
	 */
private final long checkSessionTimeout() {
    long nextTimeout = 0;
    if (configuration.getCheckSessionTimeoutInterval() > 0) {
        gate.lock();
        try {
            if (selectTries * 1000 >= configuration.getCheckSessionTimeoutInterval()) {
                nextTimeout = configuration.getCheckSessionTimeoutInterval();
                for (SelectionKey key : selector.keys()) {
                    if (key.attachment() != null) {
                        long n = checkExpiredIdle(key, getSessionFromAttchment(key));
                        nextTimeout = n < nextTimeout ? n : nextTimeout;
                    }
                }
                selectTries = 0;
            }
        } finally {
            gate.unlock();
        }
    }
    return nextTimeout;
}
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