Search in sources :

Example 11 with SelectableChannel

use of java.nio.channels.SelectableChannel in project webpieces by deanhiller.

the class SelectorManager2 method registerChannelOnThisThread.

private void registerChannelOnThisThread(RegisterableChannelImpl channel, int validOps, Object listener) {
    if (channel == null)
        throw new IllegalArgumentException("cannot register a null channel");
    else if (!Thread.currentThread().equals(selector.getThread()))
        throw new IllegalArgumentException("This function can only be invoked on PollingThread");
    else if (channel.isClosed())
        //do nothing if the channel is closed
        return;
    else if (!selector.isRunning())
        //do nothing if the selector is not running
        return;
    WrapperAndListener struct;
    SelectableChannel s = channel.getRealChannel();
    int previousOps = 0;
    log.trace(() -> channel + "registering2=" + s + " ops=" + Helper.opType(validOps));
    SelectionKey previous = channel.keyFor(selector);
    if (previous == null) {
        struct = new WrapperAndListener(channel);
    } else if (previous.attachment() == null) {
        struct = new WrapperAndListener(channel);
        previousOps = previous.interestOps();
    } else {
        struct = (WrapperAndListener) previous.attachment();
        previousOps = previous.interestOps();
    }
    struct.addListener(listener, validOps);
    int allOps = previousOps | validOps;
    SelectionKey key = channel.register(selector, allOps, struct);
    channel.setKey(key);
    //log.info("registering="+Helper.opType(allOps)+" opsToAdd="+Helper.opType(validOps)+" previousOps="+Helper.opType(previousOps)+" type="+type);
    //log.info(channel+"registered2="+s+" allOps="+Helper.opType(allOps)+" k="+Helper.opType(key.interestOps()));	
    log.trace(() -> channel + "registered2=" + s + " allOps=" + Helper.opType(allOps));
}
Also used : SelectionKey(java.nio.channels.SelectionKey) SelectableChannel(java.nio.channels.SelectableChannel)

Example 12 with SelectableChannel

use of java.nio.channels.SelectableChannel in project blade by biezhi.

the class ManagedSelector method processAccept.

private void processAccept(SelectionKey key) {
    SelectableChannel server = key.channel();
    SelectableChannel channel = null;
    try {
        channel = _selectorManager.doAccept(server);
        if (channel != null)
            _selectorManager.accepted(channel);
    } catch (Throwable x) {
        closeNoExceptions(channel);
        LOG.warn("Accept failed for channel " + channel, x);
    }
}
Also used : SelectableChannel(java.nio.channels.SelectableChannel)

Example 13 with SelectableChannel

use of java.nio.channels.SelectableChannel in project jetty.project by eclipse.

the class SelectChannelEndPointInterestsTest method init.

public void init(final Interested interested) throws Exception {
    threadPool = new QueuedThreadPool();
    threadPool.start();
    scheduler = new TimerScheduler();
    scheduler.start();
    connector = ServerSocketChannel.open();
    connector.bind(new InetSocketAddress("localhost", 0));
    selectorManager = new SelectorManager(threadPool, scheduler) {

        @Override
        protected EndPoint newEndPoint(SelectableChannel channel, ManagedSelector selector, SelectionKey key) throws IOException {
            SocketChannelEndPoint endp = new SocketChannelEndPoint(channel, selector, key, getScheduler()) {

                @Override
                protected void onIncompleteFlush() {
                    super.onIncompleteFlush();
                    interested.onIncompleteFlush();
                }
            };
            endp.setIdleTimeout(60000);
            return endp;
        }

        @Override
        public Connection newConnection(SelectableChannel channel, final EndPoint endPoint, Object attachment) {
            return new AbstractConnection(endPoint, getExecutor()) {

                @Override
                public void onOpen() {
                    super.onOpen();
                    fillInterested();
                }

                @Override
                public void onFillable() {
                    interested.onFillable(endPoint, this);
                }
            };
        }
    };
    selectorManager.start();
}
Also used : SelectionKey(java.nio.channels.SelectionKey) TimerScheduler(org.eclipse.jetty.util.thread.TimerScheduler) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) SelectableChannel(java.nio.channels.SelectableChannel) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool)

Example 14 with SelectableChannel

use of java.nio.channels.SelectableChannel in project jetty.project by eclipse.

the class SelectorManagerTest method testConnectTimeoutBeforeSuccessfulConnect.

@Slow
@Test
public void testConnectTimeoutBeforeSuccessfulConnect() throws Exception {
    ServerSocketChannel server = ServerSocketChannel.open();
    server.bind(new InetSocketAddress("localhost", 0));
    SocketAddress address = server.getLocalAddress();
    final AtomicLong timeoutConnection = new AtomicLong();
    final long connectTimeout = 1000;
    SelectorManager selectorManager = new SelectorManager(executor, scheduler) {

        @Override
        protected EndPoint newEndPoint(SelectableChannel channel, ManagedSelector selector, SelectionKey key) throws IOException {
            SocketChannelEndPoint endp = new SocketChannelEndPoint(channel, selector, key, getScheduler());
            endp.setIdleTimeout(connectTimeout / 2);
            return endp;
        }

        @Override
        protected boolean doFinishConnect(SelectableChannel channel) throws IOException {
            try {
                long timeout = timeoutConnection.get();
                if (timeout > 0)
                    TimeUnit.MILLISECONDS.sleep(timeout);
                return super.doFinishConnect(channel);
            } catch (InterruptedException e) {
                return false;
            }
        }

        @Override
        public Connection newConnection(SelectableChannel channel, EndPoint endpoint, Object attachment) throws IOException {
            ((Callback) attachment).succeeded();
            return new AbstractConnection(endpoint, executor) {

                @Override
                public void onFillable() {
                }
            };
        }

        @Override
        protected void connectionFailed(SelectableChannel channel, Throwable ex, Object attachment) {
            ((Callback) attachment).failed(ex);
        }
    };
    selectorManager.setConnectTimeout(connectTimeout);
    selectorManager.start();
    try {
        SocketChannel client1 = SocketChannel.open();
        client1.configureBlocking(false);
        client1.connect(address);
        long timeout = connectTimeout * 2;
        timeoutConnection.set(timeout);
        final CountDownLatch latch1 = new CountDownLatch(1);
        selectorManager.connect(client1, new Callback() {

            @Override
            public void failed(Throwable x) {
                latch1.countDown();
            }
        });
        Assert.assertTrue(latch1.await(connectTimeout * 3, TimeUnit.MILLISECONDS));
        Assert.assertFalse(client1.isOpen());
        // Wait for the first connect to finish, as the selector thread is waiting in finishConnect().
        Thread.sleep(timeout);
        // Verify that after the failure we can connect successfully.
        try (SocketChannel client2 = SocketChannel.open()) {
            client2.configureBlocking(false);
            client2.connect(address);
            timeoutConnection.set(0);
            final CountDownLatch latch2 = new CountDownLatch(1);
            selectorManager.connect(client2, new Callback() {

                @Override
                public void succeeded() {
                    latch2.countDown();
                }
            });
            Assert.assertTrue(latch2.await(connectTimeout * 5, TimeUnit.MILLISECONDS));
            Assert.assertTrue(client2.isOpen());
        }
    } finally {
        selectorManager.stop();
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) Callback(org.eclipse.jetty.util.Callback) SelectableChannel(java.nio.channels.SelectableChannel) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) ServerSocketChannel(java.nio.channels.ServerSocketChannel) Test(org.junit.Test) Slow(org.eclipse.jetty.toolchain.test.annotation.Slow)

Example 15 with SelectableChannel

use of java.nio.channels.SelectableChannel in project jetty.project by eclipse.

the class ManagedSelector method processConnect.

private Runnable processConnect(SelectionKey key, final Connect connect) {
    SelectableChannel channel = key.channel();
    try {
        key.attach(connect.attachment);
        boolean connected = _selectorManager.doFinishConnect(channel);
        if (LOG.isDebugEnabled())
            LOG.debug("Connected {} {}", connected, channel);
        if (connected) {
            if (connect.timeout.cancel()) {
                key.interestOps(0);
                return new CreateEndPoint(channel, key) {

                    @Override
                    protected void failed(Throwable failure) {
                        super.failed(failure);
                        connect.failed(failure);
                    }
                };
            } else {
                throw new SocketTimeoutException("Concurrent Connect Timeout");
            }
        } else {
            throw new ConnectException();
        }
    } catch (Throwable x) {
        connect.failed(x);
        return null;
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) SelectableChannel(java.nio.channels.SelectableChannel) ConnectException(java.net.ConnectException)

Aggregations

SelectableChannel (java.nio.channels.SelectableChannel)25 SelectionKey (java.nio.channels.SelectionKey)13 IOException (java.io.IOException)5 Selector (java.nio.channels.Selector)4 SocketChannel (java.nio.channels.SocketChannel)4 Test (org.junit.Test)4 SocketTimeoutException (java.net.SocketTimeoutException)3 CancelledKeyException (java.nio.channels.CancelledKeyException)3 ClosedChannelException (java.nio.channels.ClosedChannelException)3 ServerSocketChannel (java.nio.channels.ServerSocketChannel)3 Socket (org.zeromq.ZMQ.Socket)3 ConnectException (java.net.ConnectException)2 InetSocketAddress (java.net.InetSocketAddress)2 HashMap (java.util.HashMap)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 QueuedThreadPool (org.eclipse.jetty.util.thread.QueuedThreadPool)2 ChannelException (io.netty.channel.ChannelException)1 EventLoopException (io.netty.channel.EventLoopException)1 FileDescriptor (java.io.FileDescriptor)1 Socket (java.net.Socket)1