Search in sources :

Example 71 with ServerBootstrap

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

the class SimpleChannelPoolTest method testUnhealthyChannelIsNotOffered.

/**
     * Tests that if channel was unhealthy it is not offered back to the pool.
     *
     * @throws Exception
     */
@Test
public void testUnhealthyChannelIsNotOffered() throws Exception {
    EventLoopGroup group = new LocalEventLoopGroup();
    LocalAddress addr = new LocalAddress(LOCAL_ADDR_ID);
    Bootstrap cb = new Bootstrap();
    cb.remoteAddress(addr);
    cb.group(group).channel(LocalChannel.class);
    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());
        }
    });
    // Start server
    Channel sc = sb.bind(addr).syncUninterruptibly().channel();
    ChannelPoolHandler handler = new CountingChannelPoolHandler();
    ChannelPool pool = new SimpleChannelPool(cb, handler);
    Channel channel1 = pool.acquire().syncUninterruptibly().getNow();
    pool.release(channel1).syncUninterruptibly();
    Channel channel2 = pool.acquire().syncUninterruptibly().getNow();
    //first check that when returned healthy then it actually offered back to the pool.
    assertSame(channel1, channel2);
    expectedException.expect(IllegalStateException.class);
    channel1.close().syncUninterruptibly();
    try {
        pool.release(channel1).syncUninterruptibly();
    } finally {
        sc.close().syncUninterruptibly();
        channel2.close().syncUninterruptibly();
        group.shutdownGracefully();
    }
}
Also used : LocalEventLoopGroup(io.netty.channel.local.LocalEventLoopGroup) LocalAddress(io.netty.channel.local.LocalAddress) LocalChannel(io.netty.channel.local.LocalChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Channel(io.netty.channel.Channel) LocalChannel(io.netty.channel.local.LocalChannel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ExpectedException(org.junit.rules.ExpectedException) EventLoopGroup(io.netty.channel.EventLoopGroup) LocalEventLoopGroup(io.netty.channel.local.LocalEventLoopGroup) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 72 with ServerBootstrap

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

the class HttpClientCodecTest method testServerCloseSocketInputProvidesData.

@Test
public void testServerCloseSocketInputProvidesData() throws InterruptedException {
    ServerBootstrap sb = new ServerBootstrap();
    Bootstrap cb = new Bootstrap();
    final CountDownLatch serverChannelLatch = new CountDownLatch(1);
    final CountDownLatch responseRecievedLatch = new CountDownLatch(1);
    try {
        sb.group(new NioEventLoopGroup(2));
        sb.channel(NioServerSocketChannel.class);
        sb.childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                // Don't use the HttpServerCodec, because we don't want to have content-length or anything added.
                ch.pipeline().addLast(new HttpRequestDecoder(4096, 8192, 8192, true));
                ch.pipeline().addLast(new HttpObjectAggregator(4096));
                ch.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpRequest>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) {
                        // This is just a simple demo...don't block in IO
                        assertTrue(ctx.channel() instanceof SocketChannel);
                        final SocketChannel sChannel = (SocketChannel) ctx.channel();
                        /**
                             * The point of this test is to not add any content-length or content-encoding headers
                             * and the client should still handle this.
                             * See <a href="https://tools.ietf.org/html/rfc7230#section-3.3.3">RFC 7230, 3.3.3</a>.
                             */
                        sChannel.writeAndFlush(Unpooled.wrappedBuffer(("HTTP/1.0 200 OK\r\n" + "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n" + "Content-Type: text/html\r\n\r\n").getBytes(CharsetUtil.ISO_8859_1))).addListener(new ChannelFutureListener() {

                            @Override
                            public void operationComplete(ChannelFuture future) throws Exception {
                                assertTrue(future.isSuccess());
                                sChannel.writeAndFlush(Unpooled.wrappedBuffer("<html><body>hello half closed!</body></html>\r\n".getBytes(CharsetUtil.ISO_8859_1))).addListener(new ChannelFutureListener() {

                                    @Override
                                    public void operationComplete(ChannelFuture future) throws Exception {
                                        assertTrue(future.isSuccess());
                                        sChannel.shutdownOutput();
                                    }
                                });
                            }
                        });
                    }
                });
                serverChannelLatch.countDown();
            }
        });
        cb.group(new NioEventLoopGroup(1));
        cb.channel(NioSocketChannel.class);
        cb.option(ChannelOption.ALLOW_HALF_CLOSURE, true);
        cb.handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(new HttpClientCodec(4096, 8192, 8192, true, true));
                ch.pipeline().addLast(new HttpObjectAggregator(4096));
                ch.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpResponse>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) {
                        responseRecievedLatch.countDown();
                    }
                });
            }
        });
        Channel serverChannel = sb.bind(new InetSocketAddress(0)).sync().channel();
        int port = ((InetSocketAddress) serverChannel.localAddress()).getPort();
        ChannelFuture ccf = cb.connect(new InetSocketAddress(NetUtil.LOCALHOST, port));
        assertTrue(ccf.awaitUninterruptibly().isSuccess());
        Channel clientChannel = ccf.channel();
        assertTrue(serverChannelLatch.await(5, SECONDS));
        clientChannel.writeAndFlush(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"));
        assertTrue(responseRecievedLatch.await(5, SECONDS));
    } finally {
        sb.config().group().shutdownGracefully();
        sb.config().childGroup().shutdownGracefully();
        cb.config().group().shutdownGracefully();
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) PrematureChannelClosureException(io.netty.handler.codec.PrematureChannelClosureException) CodecException(io.netty.handler.codec.CodecException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.Test)

Example 73 with ServerBootstrap

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

the class EpollSocketTestPermutation method serverSocket.

@SuppressWarnings("unchecked")
@Override
public List<BootstrapFactory<ServerBootstrap>> serverSocket() {
    List<BootstrapFactory<ServerBootstrap>> toReturn = new ArrayList<BootstrapFactory<ServerBootstrap>>();
    toReturn.add(new BootstrapFactory<ServerBootstrap>() {

        @Override
        public ServerBootstrap newInstance() {
            return new ServerBootstrap().group(EPOLL_BOSS_GROUP, EPOLL_WORKER_GROUP).channel(EpollServerSocketChannel.class);
        }
    });
    if (isServerFastOpen()) {
        toReturn.add(new BootstrapFactory<ServerBootstrap>() {

            @Override
            public ServerBootstrap newInstance() {
                ServerBootstrap serverBootstrap = new ServerBootstrap().group(EPOLL_BOSS_GROUP, EPOLL_WORKER_GROUP).channel(EpollServerSocketChannel.class);
                serverBootstrap.option(EpollChannelOption.TCP_FASTOPEN, 5);
                return serverBootstrap;
            }
        });
    }
    toReturn.add(new BootstrapFactory<ServerBootstrap>() {

        @Override
        public ServerBootstrap newInstance() {
            return new ServerBootstrap().group(nioBossGroup, nioWorkerGroup).channel(NioServerSocketChannel.class);
        }
    });
    return toReturn;
}
Also used : BootstrapFactory(io.netty.testsuite.transport.TestsuitePermutation.BootstrapFactory) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ArrayList(java.util.ArrayList) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 74 with ServerBootstrap

use of io.netty.bootstrap.ServerBootstrap 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 75 with ServerBootstrap

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

the class EpollReuseAddrTest method testMultipleBindSocketChannel.

@Test(timeout = 10000)
public void testMultipleBindSocketChannel() throws Exception {
    Assume.assumeTrue(versionEqOrGt(3, 9, 0));
    ServerBootstrap bootstrap = createServerBootstrap();
    bootstrap.option(EpollChannelOption.SO_REUSEPORT, true);
    final AtomicBoolean accepted1 = new AtomicBoolean();
    bootstrap.childHandler(new ServerSocketTestHandler(accepted1));
    ChannelFuture future = bootstrap.bind().syncUninterruptibly();
    InetSocketAddress address1 = (InetSocketAddress) future.channel().localAddress();
    final AtomicBoolean accepted2 = new AtomicBoolean();
    bootstrap.childHandler(new ServerSocketTestHandler(accepted2));
    ChannelFuture future2 = bootstrap.bind().syncUninterruptibly();
    InetSocketAddress address2 = (InetSocketAddress) future2.channel().localAddress();
    Assert.assertEquals(address1, address2);
    while (!accepted1.get() || !accepted2.get()) {
        Socket socket = new Socket(address1.getAddress(), address1.getPort());
        socket.setReuseAddress(true);
        socket.close();
    }
    future.channel().close().syncUninterruptibly();
    future2.channel().close().syncUninterruptibly();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) InetSocketAddress(java.net.InetSocketAddress) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Socket(java.net.Socket) DatagramSocket(java.net.DatagramSocket) Test(org.junit.Test)

Aggregations

ServerBootstrap (io.netty.bootstrap.ServerBootstrap)177 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)87 Channel (io.netty.channel.Channel)84 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)80 EventLoopGroup (io.netty.channel.EventLoopGroup)73 ChannelFuture (io.netty.channel.ChannelFuture)63 Bootstrap (io.netty.bootstrap.Bootstrap)62 Test (org.junit.Test)59 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)48 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)45 InetSocketAddress (java.net.InetSocketAddress)40 SocketChannel (io.netty.channel.socket.SocketChannel)37 LoggingHandler (io.netty.handler.logging.LoggingHandler)36 ChannelPipeline (io.netty.channel.ChannelPipeline)34 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 SslContext (io.netty.handler.ssl.SslContext)24 LocalChannel (io.netty.channel.local.LocalChannel)23