Search in sources :

Example 51 with Bootstrap

use of io.netty.bootstrap.Bootstrap 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 52 with Bootstrap

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

the class UdtNetty method main.

public static void main(final String[] args) throws Exception {
    log.info("init");
    TrafficControl.delay(0);
    final AtomicBoolean isOn = new AtomicBoolean(true);
    final InetSocketAddress addr1 = UnitHelp.localSocketAddress();
    final InetSocketAddress addr2 = UnitHelp.localSocketAddress();
    final ChannelHandler handler1 = new EchoMessageHandler(rate, size);
    final ChannelHandler handler2 = new EchoMessageHandler(null, size);
    final NioEventLoopGroup group1 = new NioEventLoopGroup(1, Executors.defaultThreadFactory(), NioUdtProvider.MESSAGE_PROVIDER);
    final NioEventLoopGroup group2 = new NioEventLoopGroup(1, Executors.defaultThreadFactory(), NioUdtProvider.MESSAGE_PROVIDER);
    final Bootstrap peerBoot1 = new Bootstrap();
    peerBoot1.group(group1).channelFactory(NioUdtProvider.MESSAGE_RENDEZVOUS).localAddress(addr1).remoteAddress(addr2).handler(handler1);
    final Bootstrap peerBoot2 = new Bootstrap();
    peerBoot2.group(group2).channelFactory(NioUdtProvider.MESSAGE_RENDEZVOUS).localAddress(addr2).remoteAddress(addr1).handler(handler2);
    final ChannelFuture peerFuture1 = peerBoot1.connect();
    final ChannelFuture peerFuture2 = peerBoot2.connect();
    CustomReporter.enable(3, TimeUnit.SECONDS);
    Thread.sleep(time);
    isOn.set(false);
    Thread.sleep(1000);
    peerFuture1.channel().close().sync();
    peerFuture2.channel().close().sync();
    Thread.sleep(1000);
    group1.shutdownGracefully();
    group2.shutdownGracefully();
    Metrics.defaultRegistry().shutdown();
    TrafficControl.delay(0);
    log.info("done");
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) InetSocketAddress(java.net.InetSocketAddress) EchoMessageHandler(io.netty.test.udt.util.EchoMessageHandler) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelHandler(io.netty.channel.ChannelHandler) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 53 with Bootstrap

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

the class NioUdtMessageRendezvousChannelTest method basicEcho.

/**
     * verify basic echo message rendezvous
     *
     * FIXME: Re-enable after making it pass on Windows without unncessary tight loop.
     *        https://github.com/netty/netty/issues/2853
     */
@Test(timeout = 10 * 1000)
@Ignore
public void basicEcho() throws Exception {
    final int messageSize = 64 * 1024;
    final int transferLimit = messageSize * 16;
    final Meter rate1 = Metrics.newMeter(NioUdtMessageRendezvousChannelTest.class, "send rate", "bytes", TimeUnit.SECONDS);
    final Meter rate2 = Metrics.newMeter(NioUdtMessageRendezvousChannelTest.class, "send rate", "bytes", TimeUnit.SECONDS);
    final InetSocketAddress addr1 = UnitHelp.localSocketAddress();
    final InetSocketAddress addr2 = UnitHelp.localSocketAddress();
    final EchoMessageHandler handler1 = new EchoMessageHandler(rate1, messageSize);
    final EchoMessageHandler handler2 = new EchoMessageHandler(rate2, messageSize);
    final NioEventLoopGroup group1 = new NioEventLoopGroup(1, Executors.defaultThreadFactory(), NioUdtProvider.MESSAGE_PROVIDER);
    final NioEventLoopGroup group2 = new NioEventLoopGroup(1, Executors.defaultThreadFactory(), NioUdtProvider.MESSAGE_PROVIDER);
    final Bootstrap boot1 = new Bootstrap();
    boot1.group(group1).channelFactory(NioUdtProvider.MESSAGE_RENDEZVOUS).localAddress(addr1).remoteAddress(addr2).handler(handler1);
    final Bootstrap boot2 = new Bootstrap();
    boot2.group(group2).channelFactory(NioUdtProvider.MESSAGE_RENDEZVOUS).localAddress(addr2).remoteAddress(addr1).handler(handler2);
    final ChannelFuture connectFuture1 = boot1.connect();
    final ChannelFuture connectFuture2 = boot2.connect();
    while (handler1.meter().count() < transferLimit && handler2.meter().count() < transferLimit) {
        log.info("progress : {} {}", handler1.meter().count(), handler2.meter().count());
        Thread.sleep(1000);
    }
    connectFuture1.channel().close().sync();
    connectFuture2.channel().close().sync();
    log.info("handler1 : {}", handler1.meter().count());
    log.info("handler2 : {}", handler2.meter().count());
    assertTrue(handler1.meter().count() >= transferLimit);
    assertTrue(handler2.meter().count() >= transferLimit);
    assertEquals(handler1.meter().count(), handler2.meter().count());
    group1.shutdownGracefully();
    group2.shutdownGracefully();
    group1.terminationFuture().sync();
    group2.terminationFuture().sync();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Meter(com.yammer.metrics.core.Meter) InetSocketAddress(java.net.InetSocketAddress) EchoMessageHandler(io.netty.test.udt.util.EchoMessageHandler) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 54 with Bootstrap

use of io.netty.bootstrap.Bootstrap 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 55 with Bootstrap

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

the class EpollReuseAddrTest method testMultipleBindDatagramChannel.

@Test(timeout = 10000)
// TODO: Unignore after making it pass on centos6-1 and debian7-1
@Ignore
public void testMultipleBindDatagramChannel() throws Exception {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);
    Assume.assumeTrue(versionEqOrGt(3, 9, 0));
    Bootstrap bootstrap = createBootstrap();
    bootstrap.option(EpollChannelOption.SO_REUSEPORT, true);
    final AtomicBoolean received1 = new AtomicBoolean();
    bootstrap.handler(new DatagramSocketTestHandler(received1));
    ChannelFuture future = bootstrap.bind().syncUninterruptibly();
    final InetSocketAddress address1 = (InetSocketAddress) future.channel().localAddress();
    final AtomicBoolean received2 = new AtomicBoolean();
    bootstrap.handler(new DatagramSocketTestHandler(received2));
    ChannelFuture future2 = bootstrap.bind().syncUninterruptibly();
    final InetSocketAddress address2 = (InetSocketAddress) future2.channel().localAddress();
    Assert.assertEquals(address1, address2);
    final byte[] bytes = "data".getBytes();
    // fire up 16 Threads and send DatagramPackets to make sure we stress it enough to see DatagramPackets received
    // on both sockets.
    int count = 16;
    final CountDownLatch latch = new CountDownLatch(count);
    Runnable r = new Runnable() {

        @Override
        public void run() {
            try {
                DatagramSocket socket = new DatagramSocket();
                while (!received1.get() || !received2.get()) {
                    socket.send(new DatagramPacket(bytes, 0, bytes.length, address1.getAddress(), address1.getPort()));
                }
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            latch.countDown();
        }
    };
    ExecutorService executor = Executors.newFixedThreadPool(count);
    for (int i = 0; i < count; i++) {
        executor.execute(r);
    }
    latch.await();
    executor.shutdown();
    future.channel().close().syncUninterruptibly();
    future2.channel().close().syncUninterruptibly();
    Assert.assertTrue(received1.get());
    Assert.assertTrue(received2.get());
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) ExecutorService(java.util.concurrent.ExecutorService) AbstractBootstrap(io.netty.bootstrap.AbstractBootstrap) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

Bootstrap (io.netty.bootstrap.Bootstrap)163 Channel (io.netty.channel.Channel)81 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)73 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)68 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)68 ChannelFuture (io.netty.channel.ChannelFuture)62 EventLoopGroup (io.netty.channel.EventLoopGroup)61 Test (org.junit.Test)61 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)49 InetSocketAddress (java.net.InetSocketAddress)49 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)37 SocketChannel (io.netty.channel.socket.SocketChannel)33 ChannelPipeline (io.netty.channel.ChannelPipeline)31 LocalAddress (io.netty.channel.local.LocalAddress)26 ClosedChannelException (java.nio.channels.ClosedChannelException)26 LocalChannel (io.netty.channel.local.LocalChannel)22 LocalServerChannel (io.netty.channel.local.LocalServerChannel)22 CountDownLatch (java.util.concurrent.CountDownLatch)22 ChannelFutureListener (io.netty.channel.ChannelFutureListener)20 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)18