Search in sources :

Example 26 with SimpleChannelInboundHandler

use of io.netty.channel.SimpleChannelInboundHandler 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) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) NetworkChannel(java.nio.channels.NetworkChannel) 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) IOException(java.io.IOException) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoop(io.netty.channel.EventLoop) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 27 with SimpleChannelInboundHandler

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

the class Http2ClientFrameInitializer method initChannel.

@Override
protected void initChannel(Channel ch) throws Exception {
    // ensure that our 'trust all' SSL handler is the first in the pipeline if SSL is enabled.
    if (sslCtx != null) {
        ch.pipeline().addFirst(sslCtx.newHandler(ch.alloc()));
    }
    final Http2FrameCodec http2FrameCodec = Http2FrameCodecBuilder.forClient().initialSettings(// this is the default, but shows it can be changed.
    Http2Settings.defaultSettings()).build();
    ch.pipeline().addLast(http2FrameCodec);
    ch.pipeline().addLast(new Http2MultiplexHandler(new SimpleChannelInboundHandler() {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
        // NOOP (this is the handler for 'inbound' streams, which is not relevant in this example)
        }
    }));
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) Http2MultiplexHandler(io.netty.handler.codec.http2.Http2MultiplexHandler) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Http2FrameCodec(io.netty.handler.codec.http2.Http2FrameCodec)

Example 28 with SimpleChannelInboundHandler

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

the class SocketDataReadInitialStateTest method testAutoReadOnDataReadImmediately.

public void testAutoReadOnDataReadImmediately(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    Channel serverChannel = null;
    Channel clientChannel = null;
    try {
        sb.option(AUTO_READ, true);
        sb.childOption(AUTO_READ, true);
        cb.option(AUTO_READ, true);
        final CountDownLatch serverReadLatch = new CountDownLatch(1);
        final CountDownLatch clientReadLatch = new CountDownLatch(1);
        sb.childHandler(new ChannelInitializer<Channel>() {

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

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
                        ctx.writeAndFlush(msg.retainedDuplicate());
                        serverReadLatch.countDown();
                    }
                });
            }
        });
        cb.handler(new ChannelInitializer<Channel>() {

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

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
                        clientReadLatch.countDown();
                    }
                });
            }
        });
        serverChannel = sb.bind().sync().channel();
        clientChannel = cb.connect(serverChannel.localAddress()).sync().channel();
        clientChannel.writeAndFlush(clientChannel.alloc().buffer().writeZero(1)).syncUninterruptibly();
        serverReadLatch.await();
        clientReadLatch.await();
    } finally {
        if (serverChannel != null) {
            serverChannel.close().sync();
        }
        if (clientChannel != null) {
            clientChannel.close().sync();
        }
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf)

Example 29 with SimpleChannelInboundHandler

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

the class TcpDnsServer method clientQuery.

// copy from TcpDnsClient.java
private static void clientQuery() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) {
                ch.pipeline().addLast(new TcpDnsQueryEncoder()).addLast(new TcpDnsResponseDecoder()).addLast(new SimpleChannelInboundHandler<DefaultDnsResponse>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, DefaultDnsResponse msg) {
                        try {
                            handleQueryResp(msg);
                        } finally {
                            ctx.close();
                        }
                    }
                });
            }
        });
        final Channel ch = b.connect(DNS_SERVER_HOST, DNS_SERVER_PORT).sync().channel();
        int randomID = new Random().nextInt(60000 - 1000) + 1000;
        DnsQuery query = new DefaultDnsQuery(randomID, DnsOpCode.QUERY).setRecord(DnsSection.QUESTION, new DefaultDnsQuestion(QUERY_DOMAIN, DnsRecordType.A));
        ch.writeAndFlush(query).sync();
        boolean success = ch.closeFuture().await(10, TimeUnit.SECONDS);
        if (!success) {
            System.err.println("dns query timeout!");
            ch.close().sync();
        }
    } finally {
        group.shutdownGracefully();
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) TcpDnsQueryEncoder(io.netty.handler.codec.dns.TcpDnsQueryEncoder) DefaultDnsResponse(io.netty.handler.codec.dns.DefaultDnsResponse) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Random(java.util.Random) DefaultDnsQuery(io.netty.handler.codec.dns.DefaultDnsQuery) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) DefaultDnsQuery(io.netty.handler.codec.dns.DefaultDnsQuery) DnsQuery(io.netty.handler.codec.dns.DnsQuery) TcpDnsResponseDecoder(io.netty.handler.codec.dns.TcpDnsResponseDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) DefaultDnsQuestion(io.netty.handler.codec.dns.DefaultDnsQuestion)

Example 30 with SimpleChannelInboundHandler

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

the class HAProxyIntegrationTest method testBasicCase.

@Test
public void testBasicCase() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<HAProxyMessage> msgHolder = new AtomicReference<HAProxyMessage>();
    LocalAddress localAddress = new LocalAddress("HAProxyIntegrationTest");
    EventLoopGroup group = new DefaultEventLoopGroup();
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(LocalServerChannel.class).group(group).childHandler(new ChannelInitializer() {

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

                @Override
                protected void channelRead0(ChannelHandlerContext ctx, HAProxyMessage msg) throws Exception {
                    msgHolder.set(msg.retain());
                    latch.countDown();
                }
            });
        }
    });
    Channel serverChannel = sb.bind(localAddress).sync().channel();
    Bootstrap b = new Bootstrap();
    Channel clientChannel = b.channel(LocalChannel.class).handler(HAProxyMessageEncoder.INSTANCE).group(group).connect(localAddress).sync().channel();
    try {
        HAProxyMessage message = new HAProxyMessage(HAProxyProtocolVersion.V1, HAProxyCommand.PROXY, HAProxyProxiedProtocol.TCP4, "192.168.0.1", "192.168.0.11", 56324, 443);
        clientChannel.writeAndFlush(message).sync();
        assertTrue(latch.await(5, TimeUnit.SECONDS));
        HAProxyMessage readMessage = msgHolder.get();
        assertEquals(message.protocolVersion(), readMessage.protocolVersion());
        assertEquals(message.command(), readMessage.command());
        assertEquals(message.proxiedProtocol(), readMessage.proxiedProtocol());
        assertEquals(message.sourceAddress(), readMessage.sourceAddress());
        assertEquals(message.destinationAddress(), readMessage.destinationAddress());
        assertEquals(message.sourcePort(), readMessage.sourcePort());
        assertEquals(message.destinationPort(), readMessage.destinationPort());
        readMessage.release();
    } finally {
        clientChannel.close().sync();
        serverChannel.close().sync();
        group.shutdownGracefully().sync();
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) 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) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) Test(org.junit.jupiter.api.Test)

Aggregations

ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)30 SimpleChannelInboundHandler (io.netty.channel.SimpleChannelInboundHandler)30 Channel (io.netty.channel.Channel)24 Bootstrap (io.netty.bootstrap.Bootstrap)19 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)19 SocketChannel (io.netty.channel.socket.SocketChannel)16 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)16 EventLoopGroup (io.netty.channel.EventLoopGroup)13 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)11 ChannelPipeline (io.netty.channel.ChannelPipeline)11 ByteBuf (io.netty.buffer.ByteBuf)9 ChannelFuture (io.netty.channel.ChannelFuture)9 CountDownLatch (java.util.concurrent.CountDownLatch)9 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)8 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)6 HttpRequest (io.netty.handler.codec.http.HttpRequest)6 IOException (java.io.IOException)6 Random (java.util.Random)6 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)5 InetSocketAddress (java.net.InetSocketAddress)5