Search in sources :

Example 56 with EventLoopGroup

use of io.netty.channel.EventLoopGroup in project netty by netty.

the class ServerBootstrap method init.

@Override
void init(Channel channel) throws Exception {
    final Map<ChannelOption<?>, Object> options = options0();
    synchronized (options) {
        setChannelOptions(channel, options, logger);
    }
    final Map<AttributeKey<?>, Object> attrs = attrs0();
    synchronized (attrs) {
        for (Entry<AttributeKey<?>, Object> e : attrs.entrySet()) {
            @SuppressWarnings("unchecked") AttributeKey<Object> key = (AttributeKey<Object>) e.getKey();
            channel.attr(key).set(e.getValue());
        }
    }
    ChannelPipeline p = channel.pipeline();
    final EventLoopGroup currentChildGroup = childGroup;
    final ChannelHandler currentChildHandler = childHandler;
    final Entry<ChannelOption<?>, Object>[] currentChildOptions;
    final Entry<AttributeKey<?>, Object>[] currentChildAttrs;
    synchronized (childOptions) {
        currentChildOptions = childOptions.entrySet().toArray(newOptionArray(childOptions.size()));
    }
    synchronized (childAttrs) {
        currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(childAttrs.size()));
    }
    p.addLast(new ChannelInitializer<Channel>() {

        @Override
        public void initChannel(final Channel ch) throws Exception {
            final ChannelPipeline pipeline = ch.pipeline();
            ChannelHandler handler = config.handler();
            if (handler != null) {
                pipeline.addLast(handler);
            }
            // We add this handler via the EventLoop as the user may have used a ChannelInitializer as handler.
            // In this case the initChannel(...) method will only be called after this method returns. Because
            // of this we need to ensure we add our handler in a delayed fashion so all the users handler are
            // placed in front of the ServerBootstrapAcceptor.
            ch.eventLoop().execute(new Runnable() {

                @Override
                public void run() {
                    pipeline.addLast(new ServerBootstrapAcceptor(ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
                }
            });
        }
    });
}
Also used : ChannelOption(io.netty.channel.ChannelOption) ServerChannel(io.netty.channel.ServerChannel) Channel(io.netty.channel.Channel) ChannelHandler(io.netty.channel.ChannelHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) AttributeKey(io.netty.util.AttributeKey) Entry(java.util.Map.Entry) EventLoopGroup(io.netty.channel.EventLoopGroup)

Example 57 with EventLoopGroup

use of io.netty.channel.EventLoopGroup in project netty by netty.

the class EpollSpliceTest method spliceToFile.

@Test
public void spliceToFile() throws Throwable {
    EventLoopGroup group = new EpollEventLoopGroup(1);
    File file = File.createTempFile("netty-splice", null);
    file.deleteOnExit();
    SpliceHandler sh = new SpliceHandler(file);
    ServerBootstrap bs = new ServerBootstrap();
    bs.channel(EpollServerSocketChannel.class);
    bs.group(group).childHandler(sh);
    bs.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    Channel sc = bs.bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
    Bootstrap cb = new Bootstrap();
    cb.group(group);
    cb.channel(EpollSocketChannel.class);
    cb.handler(new ChannelInboundHandlerAdapter());
    Channel cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();
    for (int i = 0; i < data.length; ) {
        int length = Math.min(random.nextInt(1024 * 64), data.length - i);
        ByteBuf buf = Unpooled.wrappedBuffer(data, i, length);
        cc.writeAndFlush(buf);
        i += length;
    }
    while (sh.future == null || !sh.future.isDone()) {
        if (sh.exception.get() != null) {
            break;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        // Ignore.
        }
    }
    sc.close().sync();
    cc.close().sync();
    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
        throw sh.exception.get();
    }
    byte[] written = new byte[data.length];
    FileInputStream in = new FileInputStream(file);
    try {
        Assert.assertEquals(written.length, in.read(written));
        Assert.assertArrayEquals(data, written);
    } finally {
        in.close();
        group.shutdownGracefully();
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) IOException(java.io.IOException) ByteBuf(io.netty.buffer.ByteBuf) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) FileInputStream(java.io.FileInputStream) EventLoopGroup(io.netty.channel.EventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) File(java.io.File) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 58 with EventLoopGroup

use of io.netty.channel.EventLoopGroup in project netty by netty.

the class EpollSocketChannelTest method testTcpInfoReuse.

@Test
public void testTcpInfoReuse() throws Exception {
    EventLoopGroup group = new EpollEventLoopGroup(1);
    try {
        Bootstrap bootstrap = new Bootstrap();
        EpollSocketChannel ch = (EpollSocketChannel) bootstrap.group(group).channel(EpollSocketChannel.class).handler(new ChannelInboundHandlerAdapter()).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        EpollTcpInfo info = new EpollTcpInfo();
        ch.tcpInfo(info);
        assertTcpInfo0(info);
        ch.close().syncUninterruptibly();
    } finally {
        group.shutdownGracefully();
    }
}
Also used : EventLoopGroup(io.netty.channel.EventLoopGroup) InetSocketAddress(java.net.InetSocketAddress) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 59 with EventLoopGroup

use of io.netty.channel.EventLoopGroup in project netty by netty.

the class Http2StreamChannelBootstrap method connect.

/**
     * Used by the {@link Http2MultiplexCodec} to instantiate incoming/remotely-created streams.
     */
ChannelFuture connect(int streamId) {
    validateState();
    ParentChannelAndMultiplexCodec channelAndCodec0 = channelAndCodec;
    Channel parentChannel = channelAndCodec0.parentChannel;
    Http2MultiplexCodec multiplexCodec = channelAndCodec0.multiplexCodec;
    EventLoopGroup group0 = group;
    group0 = group0 == null ? parentChannel.eventLoop() : group0;
    return multiplexCodec.createStreamChannel(parentChannel, group0, handler, options, attributes, streamId);
}
Also used : EventLoopGroup(io.netty.channel.EventLoopGroup) Channel(io.netty.channel.Channel)

Example 60 with EventLoopGroup

use of io.netty.channel.EventLoopGroup in project netty by netty.

the class SslHandlerTest method testCloseNotify.

private static void testCloseNotify(SslProvider provider, final long closeNotifyReadTimeout, final boolean timeout) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider).build();
    final SslContext sslClientCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(provider).build();
    EventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    Channel cc = null;
    try {
        final Promise<Channel> clientPromise = group.next().newPromise();
        final Promise<Channel> serverPromise = group.next().newPromise();
        sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                SslHandler handler = sslServerCtx.newHandler(ch.alloc());
                handler.setCloseNotifyReadTimeoutMillis(closeNotifyReadTimeout);
                handler.sslCloseFuture().addListener(new PromiseNotifier<Channel, Future<Channel>>(serverPromise));
                handler.handshakeFuture().addListener(new FutureListener<Channel>() {

                    @Override
                    public void operationComplete(Future<Channel> future) {
                        if (!future.isSuccess()) {
                            // Something bad happened during handshake fail the promise!
                            serverPromise.tryFailure(future.cause());
                        }
                    }
                });
                ch.pipeline().addLast(handler);
            }
        }).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        cc = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                final AtomicBoolean closeSent = new AtomicBoolean();
                if (timeout) {
                    ch.pipeline().addFirst(new ChannelInboundHandlerAdapter() {

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if (closeSent.get()) {
                                // Drop data on the floor so we will get a timeout while waiting for the
                                // close_notify.
                                ReferenceCountUtil.release(msg);
                            } else {
                                super.channelRead(ctx, msg);
                            }
                        }
                    });
                }
                SslHandler handler = sslClientCtx.newHandler(ch.alloc());
                handler.setCloseNotifyReadTimeoutMillis(closeNotifyReadTimeout);
                handler.sslCloseFuture().addListener(new PromiseNotifier<Channel, Future<Channel>>(clientPromise));
                handler.handshakeFuture().addListener(new FutureListener<Channel>() {

                    @Override
                    public void operationComplete(Future<Channel> future) {
                        if (future.isSuccess()) {
                            closeSent.compareAndSet(false, true);
                            future.getNow().close();
                        } else {
                            // Something bad happened during handshake fail the promise!
                            clientPromise.tryFailure(future.cause());
                        }
                    }
                });
                ch.pipeline().addLast(handler);
            }
        }).connect(sc.localAddress()).syncUninterruptibly().channel();
        serverPromise.awaitUninterruptibly();
        clientPromise.awaitUninterruptibly();
        // Server always received the close_notify as the client triggers the close sequence.
        assertTrue(serverPromise.isSuccess());
        // Depending on if we wait for the response or not the promise will be failed or not.
        if (closeNotifyReadTimeout > 0 && !timeout) {
            assertTrue(clientPromise.isSuccess());
        } else {
            assertFalse(clientPromise.isSuccess());
        }
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
        ReferenceCountUtil.release(sslServerCtx);
        ReferenceCountUtil.release(sslClientCtx);
    }
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) PromiseNotifier(io.netty.util.concurrent.PromiseNotifier) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) IllegalReferenceCountException(io.netty.util.IllegalReferenceCountException) CodecException(io.netty.handler.codec.CodecException) SSLProtocolException(javax.net.ssl.SSLProtocolException) DecoderException(io.netty.handler.codec.DecoderException) SSLException(javax.net.ssl.SSLException) ClosedChannelException(java.nio.channels.ClosedChannelException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) UnsupportedMessageTypeException(io.netty.handler.codec.UnsupportedMessageTypeException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Aggregations

EventLoopGroup (io.netty.channel.EventLoopGroup)134 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)92 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)64 Channel (io.netty.channel.Channel)64 Bootstrap (io.netty.bootstrap.Bootstrap)61 Test (org.junit.Test)36 ChannelFuture (io.netty.channel.ChannelFuture)35 SslContext (io.netty.handler.ssl.SslContext)35 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)31 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)28 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)27 LoggingHandler (io.netty.handler.logging.LoggingHandler)26 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)25 SocketChannel (io.netty.channel.socket.SocketChannel)22 ChannelPipeline (io.netty.channel.ChannelPipeline)20 LocalAddress (io.netty.channel.local.LocalAddress)18 LocalChannel (io.netty.channel.local.LocalChannel)18 LocalServerChannel (io.netty.channel.local.LocalServerChannel)18 InetSocketAddress (java.net.InetSocketAddress)18 ByteBuf (io.netty.buffer.ByteBuf)17