Search in sources :

Example 1 with ChannelListener

use of org.xnio.ChannelListener in project baseio by generallycloud.

the class NioTcpChannelTestCase method main.

public static void main(String[] args) throws Exception {
    log.info("Test: acceptor");
    final CountDownLatch ioLatch = new CountDownLatch(4);
    final CountDownLatch closeLatch = new CountDownLatch(2);
    final AtomicBoolean clientOpened = new AtomicBoolean();
    final AtomicBoolean clientReadOnceOK = new AtomicBoolean();
    final AtomicBoolean clientReadDoneOK = new AtomicBoolean();
    final AtomicBoolean clientReadTooMuch = new AtomicBoolean();
    final AtomicBoolean clientWriteOK = new AtomicBoolean();
    final AtomicBoolean serverOpened = new AtomicBoolean();
    final AtomicBoolean serverReadOnceOK = new AtomicBoolean();
    final AtomicBoolean serverReadDoneOK = new AtomicBoolean();
    final AtomicBoolean serverReadTooMuch = new AtomicBoolean();
    final AtomicBoolean serverWriteOK = new AtomicBoolean();
    final byte[] bytes = "Ummagumma!".getBytes("UTF-8");
    final Xnio xnio = Xnio.getInstance("nio");
    final XnioWorker worker = xnio.createWorker(OptionMap.create(Options.WORKER_WRITE_THREADS, 2, Options.WORKER_READ_THREADS, 2));
    try {
        final FutureResult<InetSocketAddress> futureAddressResult = new FutureResult<InetSocketAddress>();
        final IoFuture<InetSocketAddress> futureAddress = futureAddressResult.getIoFuture();
        worker.acceptStream(new InetSocketAddress(Inet4Address.getByAddress(new byte[] { 127, 0, 0, 1 }), 0), new ChannelListener<ConnectedStreamChannel>() {

            private final ByteBuffer inboundBuf = ByteBuffer.allocate(512);

            private int readCnt = 0;

            private final ByteBuffer outboundBuf = ByteBuffer.wrap(bytes);

            public void handleEvent(final ConnectedStreamChannel channel) {
                channel.getCloseSetter().set(new ChannelListener<ConnectedStreamChannel>() {

                    public void handleEvent(final ConnectedStreamChannel channel) {
                        closeLatch.countDown();
                    }
                });
                channel.getReadSetter().set(new ChannelListener<ConnectedStreamChannel>() {

                    public void handleEvent(final ConnectedStreamChannel channel) {
                        try {
                            final int res = channel.read(inboundBuf);
                            if (res == -1) {
                                serverReadDoneOK.set(true);
                                ioLatch.countDown();
                                channel.shutdownReads();
                            } else if (res > 0) {
                                final int ttl = readCnt += res;
                                if (ttl == bytes.length) {
                                    serverReadOnceOK.set(true);
                                } else if (ttl > bytes.length) {
                                    serverReadTooMuch.set(true);
                                    IoUtils.safeClose(channel);
                                    return;
                                }
                            }
                        } catch (IOException e) {
                            log.errorf(e, "Server read failed");
                            IoUtils.safeClose(channel);
                        }
                    }
                });
                channel.getWriteSetter().set(new ChannelListener<ConnectedStreamChannel>() {

                    public void handleEvent(final ConnectedStreamChannel channel) {
                        try {
                            channel.write(outboundBuf);
                            if (!outboundBuf.hasRemaining()) {
                                serverWriteOK.set(true);
                                Channels.shutdownWritesBlocking(channel);
                                ioLatch.countDown();
                            }
                        } catch (IOException e) {
                            log.errorf(e, "Server write failed");
                            IoUtils.safeClose(channel);
                        }
                    }
                });
                channel.resumeReads();
                channel.resumeWrites();
                serverOpened.set(true);
            }
        }, new ChannelListener<BoundChannel>() {

            public void handleEvent(final BoundChannel channel) {
                futureAddressResult.setResult(channel.getLocalAddress(InetSocketAddress.class));
            }
        }, OptionMap.create(Options.REUSE_ADDRESSES, Boolean.TRUE));
        final InetSocketAddress localAddress = futureAddress.get();
        worker.connectStream(localAddress, new ChannelListener<ConnectedStreamChannel>() {

            private final ByteBuffer inboundBuf = ByteBuffer.allocate(512);

            private int readCnt = 0;

            private final ByteBuffer outboundBuf = ByteBuffer.wrap(bytes);

            public void handleEvent(final ConnectedStreamChannel channel) {
                channel.getCloseSetter().set(new ChannelListener<ConnectedStreamChannel>() {

                    public void handleEvent(final ConnectedStreamChannel channel) {
                        closeLatch.countDown();
                    }
                });
                channel.getReadSetter().set(new ChannelListener<ConnectedStreamChannel>() {

                    public void handleEvent(final ConnectedStreamChannel channel) {
                        try {
                            final int res = channel.read(inboundBuf);
                            if (res == -1) {
                                channel.shutdownReads();
                                clientReadDoneOK.set(true);
                                ioLatch.countDown();
                            } else if (res > 0) {
                                final int ttl = readCnt += res;
                                if (ttl == bytes.length) {
                                    clientReadOnceOK.set(true);
                                } else if (ttl > bytes.length) {
                                    clientReadTooMuch.set(true);
                                    IoUtils.safeClose(channel);
                                    return;
                                }
                            }
                        } catch (IOException e) {
                            log.errorf(e, "Client read failed");
                            IoUtils.safeClose(channel);
                        }
                    }
                });
                channel.getWriteSetter().set(new ChannelListener<ConnectedStreamChannel>() {

                    public void handleEvent(final ConnectedStreamChannel channel) {
                        try {
                            channel.write(outboundBuf);
                            if (!outboundBuf.hasRemaining()) {
                                clientWriteOK.set(true);
                                Channels.shutdownWritesBlocking(channel);
                                ioLatch.countDown();
                            }
                        } catch (IOException e) {
                            log.errorf(e, "Client write failed");
                            IoUtils.safeClose(channel);
                        }
                    }
                });
                channel.resumeReads();
                channel.resumeWrites();
                clientOpened.set(true);
            }
        }, null, OptionMap.EMPTY);
    // assertTrue("Read timed out", ioLatch.await(500L, TimeUnit.MILLISECONDS));
    // assertTrue("Close timed out", closeLatch.await(500L, TimeUnit.MILLISECONDS));
    // assertFalse("Client read too much", clientReadTooMuch.get());
    // assertTrue("Client read OK", clientReadOnceOK.get());
    // assertTrue("Client read done", clientReadDoneOK.get());
    // assertTrue("Client write OK", clientWriteOK.get());
    // assertFalse("Server read too much", serverReadTooMuch.get());
    // assertTrue("Server read OK", serverReadOnceOK.get());
    // assertTrue("Server read done", serverReadDoneOK.get());
    // assertTrue("Server write OK", serverWriteOK.get());
    } finally {
        worker.shutdown();
    }
}
Also used : ConnectedStreamChannel(org.xnio.channels.ConnectedStreamChannel) ChannelListener(org.xnio.ChannelListener) XnioWorker(org.xnio.XnioWorker) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) BoundChannel(org.xnio.channels.BoundChannel) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FutureResult(org.xnio.FutureResult) Xnio(org.xnio.Xnio)

Example 2 with ChannelListener

use of org.xnio.ChannelListener in project undertow by undertow-io.

the class AsyncWebSocketHttpServerExchange method readRequestData.

@Override
public IoFuture<byte[]> readRequestData() {
    final ByteArrayOutputStream data = new ByteArrayOutputStream();
    final PooledByteBuffer pooled = exchange.getConnection().getByteBufferPool().allocate();
    final ByteBuffer buffer = pooled.getBuffer();
    final StreamSourceChannel channel = exchange.getRequestChannel();
    int res;
    for (; ; ) {
        try {
            res = channel.read(buffer);
            if (res == -1) {
                return new FinishedIoFuture<>(data.toByteArray());
            } else if (res == 0) {
                // callback
                final FutureResult<byte[]> future = new FutureResult<>();
                channel.getReadSetter().set(new ChannelListener<StreamSourceChannel>() {

                    @Override
                    public void handleEvent(final StreamSourceChannel channel) {
                        int res;
                        try {
                            res = channel.read(buffer);
                            if (res == -1) {
                                future.setResult(data.toByteArray());
                                channel.suspendReads();
                                return;
                            } else if (res == 0) {
                                return;
                            } else {
                                buffer.flip();
                                while (buffer.hasRemaining()) {
                                    data.write(buffer.get());
                                }
                                buffer.clear();
                            }
                        } catch (IOException e) {
                            future.setException(e);
                        }
                    }
                });
                channel.resumeReads();
                return future.getIoFuture();
            } else {
                buffer.flip();
                while (buffer.hasRemaining()) {
                    data.write(buffer.get());
                }
                buffer.clear();
            }
        } catch (IOException e) {
            final FutureResult<byte[]> future = new FutureResult<>();
            future.setException(e);
            return future.getIoFuture();
        }
    }
}
Also used : StreamSourceChannel(org.xnio.channels.StreamSourceChannel) FinishedIoFuture(org.xnio.FinishedIoFuture) ChannelListener(org.xnio.ChannelListener) FutureResult(org.xnio.FutureResult) PooledByteBuffer(io.undertow.connector.PooledByteBuffer) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) PooledByteBuffer(io.undertow.connector.PooledByteBuffer)

Example 3 with ChannelListener

use of org.xnio.ChannelListener in project undertow by undertow-io.

the class UndertowXnioSsl method createSslTcpServer.

@SuppressWarnings("deprecation")
public AcceptingChannel<ConnectedSslStreamChannel> createSslTcpServer(final XnioWorker worker, final InetSocketAddress bindAddress, final ChannelListener<? super AcceptingChannel<ConnectedSslStreamChannel>> acceptListener, final OptionMap optionMap) throws IOException {
    final AcceptingChannel<SslConnection> server = createSslConnectionServer(worker, bindAddress, null, optionMap);
    final AcceptingChannel<ConnectedSslStreamChannel> acceptingChannel = new AcceptingChannel<ConnectedSslStreamChannel>() {

        public ConnectedSslStreamChannel accept() throws IOException {
            final SslConnection connection = server.accept();
            return connection == null ? null : new AssembledConnectedSslStreamChannel(connection, connection.getSourceChannel(), connection.getSinkChannel());
        }

        public ChannelListener.Setter<? extends AcceptingChannel<ConnectedSslStreamChannel>> getAcceptSetter() {
            return ChannelListeners.getDelegatingSetter(server.getAcceptSetter(), this);
        }

        public ChannelListener.Setter<? extends AcceptingChannel<ConnectedSslStreamChannel>> getCloseSetter() {
            return ChannelListeners.getDelegatingSetter(server.getCloseSetter(), this);
        }

        public SocketAddress getLocalAddress() {
            return server.getLocalAddress();
        }

        public <A extends SocketAddress> A getLocalAddress(final Class<A> type) {
            return server.getLocalAddress(type);
        }

        public void suspendAccepts() {
            server.suspendAccepts();
        }

        public void resumeAccepts() {
            server.resumeAccepts();
        }

        public boolean isAcceptResumed() {
            return server.isAcceptResumed();
        }

        public void wakeupAccepts() {
            server.wakeupAccepts();
        }

        public void awaitAcceptable() throws IOException {
            server.awaitAcceptable();
        }

        public void awaitAcceptable(final long time, final TimeUnit timeUnit) throws IOException {
            server.awaitAcceptable(time, timeUnit);
        }

        public XnioWorker getWorker() {
            return server.getWorker();
        }

        @Deprecated
        public XnioExecutor getAcceptThread() {
            return server.getAcceptThread();
        }

        public XnioIoThread getIoThread() {
            return server.getIoThread();
        }

        public void close() throws IOException {
            server.close();
        }

        public boolean isOpen() {
            return server.isOpen();
        }

        public boolean supportsOption(final Option<?> option) {
            return server.supportsOption(option);
        }

        public <T> T getOption(final Option<T> option) throws IOException {
            return server.getOption(option);
        }

        public <T> T setOption(final Option<T> option, final T value) throws IllegalArgumentException, IOException {
            return server.setOption(option, value);
        }
    };
    acceptingChannel.getAcceptSetter().set(acceptListener);
    return acceptingChannel;
}
Also used : SslConnection(org.xnio.ssl.SslConnection) ChannelListener(org.xnio.ChannelListener) TimeUnit(java.util.concurrent.TimeUnit) Option(org.xnio.Option) AssembledConnectedSslStreamChannel(org.xnio.channels.AssembledConnectedSslStreamChannel) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) ConnectedSslStreamChannel(org.xnio.channels.ConnectedSslStreamChannel) AssembledConnectedSslStreamChannel(org.xnio.channels.AssembledConnectedSslStreamChannel) AcceptingChannel(org.xnio.channels.AcceptingChannel)

Example 4 with ChannelListener

use of org.xnio.ChannelListener in project undertow by undertow-io.

the class AutobahnExtensionsServer method run.

public void run() {
    xnio = Xnio.getInstance();
    try {
        worker = xnio.createWorker(OptionMap.builder().set(Options.CONNECTION_HIGH_WATER, 1000000).set(Options.CONNECTION_LOW_WATER, 1000000).set(Options.WORKER_TASK_CORE_THREADS, 10).set(Options.WORKER_TASK_MAX_THREADS, 12).set(Options.TCP_NODELAY, true).set(Options.CORK, true).getMap());
        OptionMap serverOptions = OptionMap.builder().set(Options.TCP_NODELAY, true).set(Options.REUSE_ADDRESSES, true).getMap();
        openListener = new HttpOpenListener(new DefaultByteBufferPool(false, 8192));
        ChannelListener acceptListener = ChannelListeners.openListenerAdapter(openListener);
        server = worker.createStreamConnectionServer(new InetSocketAddress(port), acceptListener, serverOptions);
        WebSocketProtocolHandshakeHandler handler = webSocketDebugHandler().addExtension(new PerMessageDeflateHandshake());
        DebugExtensionsHeaderHandler debug = new DebugExtensionsHeaderHandler(handler);
        setRootHandler(debug);
        server.resumeAccepts();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : ChannelListener(org.xnio.ChannelListener) DefaultByteBufferPool(io.undertow.server.DefaultByteBufferPool) InetSocketAddress(java.net.InetSocketAddress) OptionMap(org.xnio.OptionMap) WebSocketProtocolHandshakeHandler(io.undertow.websockets.WebSocketProtocolHandshakeHandler) HttpOpenListener(io.undertow.server.protocol.http.HttpOpenListener) IOException(java.io.IOException)

Example 5 with ChannelListener

use of org.xnio.ChannelListener in project undertow by undertow-io.

the class AutobahnExtensionCustomReceiverServer method run.

public void run() {
    xnio = Xnio.getInstance();
    try {
        worker = xnio.createWorker(OptionMap.builder().set(Options.WORKER_WRITE_THREADS, 4).set(Options.WORKER_READ_THREADS, 4).set(Options.CONNECTION_HIGH_WATER, 1000000).set(Options.CONNECTION_LOW_WATER, 1000000).set(Options.WORKER_TASK_CORE_THREADS, 10).set(Options.WORKER_TASK_MAX_THREADS, 12).set(Options.TCP_NODELAY, true).set(Options.CORK, true).getMap());
        OptionMap serverOptions = OptionMap.builder().set(Options.WORKER_ACCEPT_THREADS, 4).set(Options.TCP_NODELAY, true).set(Options.REUSE_ADDRESSES, true).getMap();
        openListener = new HttpOpenListener(new DefaultByteBufferPool(false, 8192));
        ChannelListener acceptListener = ChannelListeners.openListenerAdapter(openListener);
        server = worker.createStreamConnectionServer(new InetSocketAddress(port), acceptListener, serverOptions);
        setRootHandler(getRootHandler().addExtension(new PerMessageDeflateHandshake()));
        server.resumeAccepts();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : ChannelListener(org.xnio.ChannelListener) DefaultByteBufferPool(io.undertow.server.DefaultByteBufferPool) InetSocketAddress(java.net.InetSocketAddress) OptionMap(org.xnio.OptionMap) HttpOpenListener(io.undertow.server.protocol.http.HttpOpenListener) IOException(java.io.IOException)

Aggregations

ChannelListener (org.xnio.ChannelListener)25 IOException (java.io.IOException)18 InetSocketAddress (java.net.InetSocketAddress)11 ByteBuffer (java.nio.ByteBuffer)8 StreamConnection (org.xnio.StreamConnection)7 DefaultByteBufferPool (io.undertow.server.DefaultByteBufferPool)6 HttpOpenListener (io.undertow.server.protocol.http.HttpOpenListener)6 OptionMap (org.xnio.OptionMap)6 PooledByteBuffer (io.undertow.connector.PooledByteBuffer)5 HttpServerExchange (io.undertow.server.HttpServerExchange)5 StreamSinkChannel (org.xnio.channels.StreamSinkChannel)5 HttpHandler (io.undertow.server.HttpHandler)4 FutureResult (org.xnio.FutureResult)4 StreamSourceChannel (org.xnio.channels.StreamSourceChannel)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 Channel (java.nio.channels.Channel)3 ChannelExceptionHandler (org.xnio.ChannelExceptionHandler)3 Xnio (org.xnio.Xnio)3 XnioWorker (org.xnio.XnioWorker)3 ConnectedStreamChannel (org.xnio.channels.ConnectedStreamChannel)3