Search in sources :

Example 26 with ServerBootstrap

use of io.netty.bootstrap.ServerBootstrap in project netty by netty.

the class LocalChannelTest method localChannelRaceCondition.

@Test
public void localChannelRaceCondition() throws Exception {
    final CountDownLatch closeLatch = new CountDownLatch(1);
    final EventLoopGroup clientGroup = new DefaultEventLoopGroup(1) {

        @Override
        protected EventLoop newChild(Executor threadFactory, Object... args) throws Exception {
            return new SingleThreadEventLoop(this, threadFactory, true) {

                @Override
                protected void run() {
                    for (; ; ) {
                        Runnable task = takeTask();
                        if (task != null) {
                            /* Only slow down the anonymous class in LocalChannel#doRegister() */
                            if (task.getClass().getEnclosingClass() == LocalChannel.class) {
                                try {
                                    closeLatch.await();
                                } catch (InterruptedException e) {
                                    throw new Error(e);
                                }
                            }
                            task.run();
                            updateLastExecutionTime();
                        }
                        if (confirmShutdown()) {
                            break;
                        }
                    }
                }
            };
        }
    };
    Channel sc = null;
    Channel cc = null;
    try {
        ServerBootstrap sb = new ServerBootstrap();
        sc = sb.group(group2).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.close();
                closeLatch.countDown();
            }
        }).bind(TEST_ADDRESS).sync().channel();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(clientGroup).channel(LocalChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
            /* Do nothing */
            }
        });
        ChannelFuture future = bootstrap.connect(sc.localAddress());
        assertTrue("Connection should finish, not time out", future.await(200));
        cc = future.channel();
    } finally {
        closeChannel(cc);
        closeChannel(sc);
        clientGroup.shutdownGracefully(0, 0, SECONDS).await();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) AbstractChannel(io.netty.channel.AbstractChannel) Channel(io.netty.channel.Channel) SingleThreadEventLoop(io.netty.channel.SingleThreadEventLoop) CountDownLatch(java.util.concurrent.CountDownLatch) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ConnectException(java.net.ConnectException) ClosedChannelException(java.nio.channels.ClosedChannelException) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) Executor(java.util.concurrent.Executor) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Test(org.junit.Test)

Example 27 with ServerBootstrap

use of io.netty.bootstrap.ServerBootstrap in project netty by netty.

the class LocalChannelTest method testConnectFutureBeforeChannelActive.

@Test(timeout = 3000)
public void testConnectFutureBeforeChannelActive() throws Exception {
    Bootstrap cb = new Bootstrap();
    ServerBootstrap sb = new ServerBootstrap();
    cb.group(group1).channel(LocalChannel.class).handler(new ChannelInboundHandlerAdapter());
    sb.group(group2).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {

        @Override
        public void initChannel(LocalChannel ch) throws Exception {
            ch.pipeline().addLast(new TestHandler());
        }
    });
    Channel sc = null;
    Channel cc = null;
    try {
        // Start server
        sc = sb.bind(TEST_ADDRESS).sync().channel();
        cc = cb.register().sync().channel();
        final ChannelPromise promise = cc.newPromise();
        final Promise<Void> assertPromise = cc.eventLoop().newPromise();
        cc.pipeline().addLast(new TestHandler() {

            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                // Ensure the promise was done before the handler method is triggered.
                if (promise.isDone()) {
                    assertPromise.setSuccess(null);
                } else {
                    assertPromise.setFailure(new AssertionError("connect promise should be done"));
                }
            }
        });
        // Connect to the server
        cc.connect(sc.localAddress(), promise).sync();
        assertPromise.syncUninterruptibly();
        assertTrue(promise.isSuccess());
    } finally {
        closeChannel(cc);
        closeChannel(sc);
    }
}
Also used : AbstractChannel(io.netty.channel.AbstractChannel) Channel(io.netty.channel.Channel) ChannelPromise(io.netty.channel.ChannelPromise) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ConnectException(java.net.ConnectException) ClosedChannelException(java.nio.channels.ClosedChannelException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 28 with ServerBootstrap

use of io.netty.bootstrap.ServerBootstrap in project netty by netty.

the class LocalTransportThreadModelTest method init.

@BeforeClass
public static void init() {
    // Configure a test server
    group = new DefaultEventLoopGroup();
    ServerBootstrap sb = new ServerBootstrap();
    sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {

        @Override
        public void initChannel(LocalChannel ch) throws Exception {
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    // Discard
                    ReferenceCountUtil.release(msg);
                }
            });
        }
    });
    localAddr = (LocalAddress) sb.bind(LocalAddress.ANY).syncUninterruptibly().channel().localAddress();
}
Also used : ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) BeforeClass(org.junit.BeforeClass)

Example 29 with ServerBootstrap

use of io.netty.bootstrap.ServerBootstrap in project netty by netty.

the class NioSocketChannelTest method testChannelReRegisterRead.

private static void testChannelReRegisterRead(final boolean sameEventLoop) throws Exception {
    final EventLoopGroup group = new NioEventLoopGroup(2);
    final CountDownLatch latch = new CountDownLatch(1);
    // Just some random bytes
    byte[] bytes = new byte[1024];
    PlatformDependent.threadLocalRandom().nextBytes(bytes);
    Channel sc = null;
    Channel cc = null;
    ServerBootstrap b = new ServerBootstrap();
    try {
        b.group(group).channel(NioServerSocketChannel.class).childOption(ChannelOption.SO_KEEPALIVE, true).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new SimpleChannelInboundHandler<ByteBuf>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) {
                        // We was able to read something from the Channel after reregister.
                        latch.countDown();
                    }

                    @Override
                    public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                        final EventLoop loop = group.next();
                        if (sameEventLoop) {
                            deregister(ctx, loop);
                        } else {
                            loop.execute(new Runnable() {

                                @Override
                                public void run() {
                                    deregister(ctx, loop);
                                }
                            });
                        }
                    }

                    private void deregister(ChannelHandlerContext ctx, final EventLoop loop) {
                        // As soon as the channel becomes active re-register it to another
                        // EventLoop. After this is done we should still receive the data that
                        // was written to the channel.
                        ctx.deregister().addListener(new ChannelFutureListener() {

                            @Override
                            public void operationComplete(ChannelFuture cf) {
                                Channel channel = cf.channel();
                                assertNotSame(loop, channel.eventLoop());
                                group.next().register(channel);
                            }
                        });
                    }
                });
            }
        });
        sc = b.bind(0).syncUninterruptibly().channel();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInboundHandlerAdapter());
        cc = bootstrap.connect(sc.localAddress()).syncUninterruptibly().channel();
        cc.writeAndFlush(Unpooled.wrappedBuffer(bytes)).syncUninterruptibly();
        latch.await();
    } finally {
        if (cc != null) {
            cc.close();
        }
        if (sc != null) {
            sc.close();
        }
        group.shutdownGracefully();
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ClosedChannelException(java.nio.channels.ClosedChannelException) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoopGroup(io.netty.channel.EventLoopGroup) EventLoop(io.netty.channel.EventLoop) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 30 with ServerBootstrap

use of io.netty.bootstrap.ServerBootstrap in project netty by netty.

the class NioSocketChannelTest method testFlushAfterGatheredFlush.

/**
     * Reproduces the issue #1679
     */
@Test
public void testFlushAfterGatheredFlush() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup(1);
    try {
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(group).channel(NioServerSocketChannel.class);
        sb.childHandler(new ChannelInboundHandlerAdapter() {

            @Override
            public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                // Trigger a gathering write by writing two buffers.
                ctx.write(Unpooled.wrappedBuffer(new byte[] { 'a' }));
                ChannelFuture f = ctx.write(Unpooled.wrappedBuffer(new byte[] { 'b' }));
                f.addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        // This message must be flushed
                        ctx.writeAndFlush(Unpooled.wrappedBuffer(new byte[] { 'c' }));
                    }
                });
                ctx.flush();
            }
        });
        SocketAddress address = sb.bind(0).sync().channel().localAddress();
        Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) address).getPort());
        DataInput in = new DataInputStream(s.getInputStream());
        byte[] buf = new byte[3];
        in.readFully(buf);
        assertThat(new String(buf, CharsetUtil.US_ASCII), is("abc"));
        s.close();
    } finally {
        group.shutdownGracefully().sync();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DataInputStream(java.io.DataInputStream) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ClosedChannelException(java.nio.channels.ClosedChannelException) DataInput(java.io.DataInput) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) Socket(java.net.Socket) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Aggregations

ServerBootstrap (io.netty.bootstrap.ServerBootstrap)166 Channel (io.netty.channel.Channel)81 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)78 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)72 EventLoopGroup (io.netty.channel.EventLoopGroup)70 Bootstrap (io.netty.bootstrap.Bootstrap)62 Test (org.junit.Test)59 ChannelFuture (io.netty.channel.ChannelFuture)58 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)48 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)45 InetSocketAddress (java.net.InetSocketAddress)38 SocketChannel (io.netty.channel.socket.SocketChannel)33 LoggingHandler (io.netty.handler.logging.LoggingHandler)33 ChannelPipeline (io.netty.channel.ChannelPipeline)31 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)29 CountDownLatch (java.util.concurrent.CountDownLatch)28 ClosedChannelException (java.nio.channels.ClosedChannelException)27 LocalAddress (io.netty.channel.local.LocalAddress)25 LocalChannel (io.netty.channel.local.LocalChannel)23 ByteBuf (io.netty.buffer.ByteBuf)22