Search in sources :

Example 66 with ChannelHandlerContext

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

the class SocketRstTest method testSoLingerZeroCausesOnlyRstOnClose.

public void testSoLingerZeroCausesOnlyRstOnClose(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    final AtomicReference<Channel> serverChannelRef = new AtomicReference<Channel>();
    final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>();
    final CountDownLatch latch = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    // SO_LINGER=0 means that we must send ONLY a RST when closing (not a FIN + RST).
    sb.childOption(ChannelOption.SO_LINGER, 0);
    sb.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            serverChannelRef.compareAndSet(null, ch);
            latch.countDown();
        }
    });
    cb.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                    throwableRef.compareAndSet(null, cause);
                }

                @Override
                public void channelInactive(ChannelHandlerContext ctx) {
                    latch2.countDown();
                }
            });
        }
    });
    Channel sc = sb.bind().sync().channel();
    Channel cc = cb.connect(sc.localAddress()).sync().channel();
    // Wait for the server to get setup.
    latch.await();
    // The server has SO_LINGER=0 and so it must send a RST when close is called.
    serverChannelRef.get().close();
    // Wait for the client to get channelInactive.
    latch2.await();
    // Verify the client received a RST.
    Throwable cause = throwableRef.get();
    assertTrue("actual [type, message]: [" + cause.getClass() + ", " + cause.getMessage() + "]", cause instanceof IOException);
    assertRstOnCloseException((IOException) cause, cc);
}
Also used : Channel(io.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 67 with ChannelHandlerContext

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

the class DatagramMulticastTest method testMulticast.

public void testMulticast(Bootstrap sb, Bootstrap cb) throws Throwable {
    MulticastTestHandler mhandler = new MulticastTestHandler();
    sb.handler(new SimpleChannelInboundHandler<Object>() {

        @Override
        public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        // Nothing will be sent.
        }
    });
    cb.handler(mhandler);
    sb.option(ChannelOption.IP_MULTICAST_IF, NetUtil.LOOPBACK_IF);
    sb.option(ChannelOption.SO_REUSEADDR, true);
    cb.option(ChannelOption.IP_MULTICAST_IF, NetUtil.LOOPBACK_IF);
    cb.option(ChannelOption.SO_REUSEADDR, true);
    cb.localAddress(addr.getPort());
    Channel sc = sb.bind().sync().channel();
    if (sc instanceof OioDatagramChannel) {
        // skip the test for OIO, as it fails because of
        // No route to host which makes no sense.
        // Maybe a JDK bug ?
        sc.close().awaitUninterruptibly();
        return;
    }
    DatagramChannel cc = (DatagramChannel) cb.bind().sync().channel();
    String group = "230.0.0.1";
    InetSocketAddress groupAddress = SocketUtils.socketAddress(group, addr.getPort());
    cc.joinGroup(groupAddress, NetUtil.LOOPBACK_IF).sync();
    sc.writeAndFlush(new DatagramPacket(Unpooled.copyInt(1), groupAddress)).sync();
    assertTrue(mhandler.await());
    // leave the group
    cc.leaveGroup(groupAddress, NetUtil.LOOPBACK_IF).sync();
    // sleep a second to make sure we left the group
    Thread.sleep(1000);
    // we should not receive a message anymore as we left the group before
    sc.writeAndFlush(new DatagramPacket(Unpooled.copyInt(1), groupAddress)).sync();
    mhandler.await();
    sc.close().awaitUninterruptibly();
    cc.close().awaitUninterruptibly();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) OioDatagramChannel(io.netty.channel.socket.oio.OioDatagramChannel) Channel(io.netty.channel.Channel) DatagramChannel(io.netty.channel.socket.DatagramChannel) OioDatagramChannel(io.netty.channel.socket.oio.OioDatagramChannel) DatagramPacket(io.netty.channel.socket.DatagramPacket) OioDatagramChannel(io.netty.channel.socket.oio.OioDatagramChannel) DatagramChannel(io.netty.channel.socket.DatagramChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext)

Example 68 with ChannelHandlerContext

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

the class DatagramUnicastTest method testSimpleSend0.

@SuppressWarnings("deprecation")
private void testSimpleSend0(Bootstrap sb, Bootstrap cb, ByteBuf buf, boolean bindClient, final byte[] bytes, int count) throws Throwable {
    final CountDownLatch latch = new CountDownLatch(count);
    sb.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new SimpleChannelInboundHandler<DatagramPacket>() {

                @Override
                public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
                    ByteBuf buf = msg.content();
                    assertEquals(bytes.length, buf.readableBytes());
                    for (byte b : bytes) {
                        assertEquals(b, buf.readByte());
                    }
                    latch.countDown();
                }
            });
        }
    });
    cb.handler(new SimpleChannelInboundHandler<Object>() {

        @Override
        public void channelRead0(ChannelHandlerContext ctx, Object msgs) throws Exception {
        // Nothing will be sent.
        }
    });
    Channel sc = null;
    BindException bindFailureCause = null;
    for (int i = 0; i < 3; i++) {
        try {
            sc = sb.bind().sync().channel();
            break;
        } catch (Exception e) {
            if (e instanceof BindException) {
                logger.warn("Failed to bind to a free port; trying again", e);
                bindFailureCause = (BindException) e;
                refreshLocalAddress(sb);
            } else {
                throw e;
            }
        }
    }
    if (sc == null) {
        throw bindFailureCause;
    }
    Channel cc;
    if (bindClient) {
        cc = cb.bind().sync().channel();
    } else {
        cb.option(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION, true);
        cc = cb.register().sync().channel();
    }
    for (int i = 0; i < count; i++) {
        cc.write(new DatagramPacket(buf.retain().duplicate(), addr));
    }
    // release as we used buf.retain() before
    buf.release();
    cc.flush();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    sc.close().sync();
    cc.close().sync();
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) Channel(io.netty.channel.Channel) BindException(java.net.BindException) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf) BindException(java.net.BindException) DatagramPacket(io.netty.channel.socket.DatagramPacket)

Example 69 with ChannelHandlerContext

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

the class SocketConnectTest method testLocalAddressAfterConnect.

public void testLocalAddressAfterConnect(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    Channel serverChannel = null;
    Channel clientChannel = null;
    try {
        final Promise<InetSocketAddress> localAddressPromise = ImmediateEventExecutor.INSTANCE.newPromise();
        serverChannel = sb.childHandler(new ChannelInboundHandlerAdapter() {

            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                localAddressPromise.setSuccess((InetSocketAddress) ctx.channel().localAddress());
            }
        }).bind().syncUninterruptibly().channel();
        clientChannel = cb.handler(new ChannelInboundHandlerAdapter()).register().syncUninterruptibly().channel();
        assertNull(clientChannel.localAddress());
        assertNull(clientChannel.remoteAddress());
        clientChannel.connect(serverChannel.localAddress()).syncUninterruptibly().channel();
        assertLocalAddress((InetSocketAddress) clientChannel.localAddress());
        assertNotNull(clientChannel.remoteAddress());
        assertLocalAddress(localAddressPromise.get());
    } finally {
        if (clientChannel != null) {
            clientChannel.close().syncUninterruptibly();
        }
        if (serverChannel != null) {
            serverChannel.close().syncUninterruptibly();
        }
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 70 with ChannelHandlerContext

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

the class SocketFileRegionTest method testFileRegion0.

private static void testFileRegion0(ServerBootstrap sb, Bootstrap cb, boolean voidPromise, final boolean autoRead, boolean defaultFileRegion) throws Throwable {
    sb.childOption(ChannelOption.AUTO_READ, autoRead);
    cb.option(ChannelOption.AUTO_READ, autoRead);
    final int bufferSize = 1024;
    final File file = File.createTempFile("netty-", ".tmp");
    file.deleteOnExit();
    final FileOutputStream out = new FileOutputStream(file);
    final Random random = PlatformDependent.threadLocalRandom();
    // Prepend random data which will not be transferred, so that we can test non-zero start offset
    final int startOffset = random.nextInt(8192);
    for (int i = 0; i < startOffset; i++) {
        out.write(random.nextInt());
    }
    // .. and here comes the real data to transfer.
    out.write(data, bufferSize, data.length - bufferSize);
    // .. and then some extra data which is not supposed to be transferred.
    for (int i = random.nextInt(8192); i > 0; i--) {
        out.write(random.nextInt());
    }
    out.close();
    ChannelInboundHandler ch = new SimpleChannelInboundHandler<Object>() {

        @Override
        public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            if (!autoRead) {
                ctx.read();
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }
    };
    TestHandler sh = new TestHandler(autoRead);
    sb.childHandler(sh);
    cb.handler(ch);
    Channel sc = sb.bind().sync().channel();
    Channel cc = cb.connect().sync().channel();
    FileRegion region = new DefaultFileRegion(new FileInputStream(file).getChannel(), startOffset, data.length - bufferSize);
    FileRegion emptyRegion = new DefaultFileRegion(new FileInputStream(file).getChannel(), 0, 0);
    if (!defaultFileRegion) {
        region = new FileRegionWrapper(region);
        emptyRegion = new FileRegionWrapper(emptyRegion);
    }
    //     https://github.com/netty/netty/issues/2964
    if (voidPromise) {
        assertEquals(cc.voidPromise(), cc.write(Unpooled.wrappedBuffer(data, 0, bufferSize), cc.voidPromise()));
        assertEquals(cc.voidPromise(), cc.write(emptyRegion, cc.voidPromise()));
        assertEquals(cc.voidPromise(), cc.writeAndFlush(region, cc.voidPromise()));
    } else {
        assertNotEquals(cc.voidPromise(), cc.write(Unpooled.wrappedBuffer(data, 0, bufferSize)));
        assertNotEquals(cc.voidPromise(), cc.write(emptyRegion));
        assertNotEquals(cc.voidPromise(), cc.writeAndFlush(region));
    }
    while (sh.counter < data.length) {
        if (sh.exception.get() != null) {
            break;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        // Ignore.
        }
    }
    sh.channel.close().sync();
    cc.close().sync();
    sc.close().sync();
    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
        throw sh.exception.get();
    }
    if (sh.exception.get() != null) {
        throw sh.exception.get();
    }
    // Make sure we did not receive more than we expected.
    assertThat(sh.counter, is(data.length));
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) Channel(io.netty.channel.Channel) WritableByteChannel(java.nio.channels.WritableByteChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) IOException(java.io.IOException) DefaultFileRegion(io.netty.channel.DefaultFileRegion) FileInputStream(java.io.FileInputStream) Random(java.util.Random) FileOutputStream(java.io.FileOutputStream) DefaultFileRegion(io.netty.channel.DefaultFileRegion) FileRegion(io.netty.channel.FileRegion) ChannelInboundHandler(io.netty.channel.ChannelInboundHandler) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) File(java.io.File)

Aggregations

ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)266 Test (org.junit.Test)150 Channel (io.netty.channel.Channel)106 ByteBuf (io.netty.buffer.ByteBuf)94 ChannelFuture (io.netty.channel.ChannelFuture)87 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)77 Bootstrap (io.netty.bootstrap.Bootstrap)69 ChannelPipeline (io.netty.channel.ChannelPipeline)68 ClosedChannelException (java.nio.channels.ClosedChannelException)63 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)57 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)56 InetSocketAddress (java.net.InetSocketAddress)54 AtomicReference (java.util.concurrent.atomic.AtomicReference)53 EventLoopGroup (io.netty.channel.EventLoopGroup)48 CountDownLatch (java.util.concurrent.CountDownLatch)47 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)45 ArrayList (java.util.ArrayList)45 List (java.util.List)43 IOException (java.io.IOException)42 Map (java.util.Map)40