Search in sources :

Example 11 with SimpleChannelInboundHandler

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

the class DoTClient method main.

public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        final SslContext sslContext = SslContextBuilder.forClient().protocols("TLSv1.3", "TLSv1.2").build();
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                p.addLast(sslContext.newHandler(ch.alloc(), DNS_SERVER_HOST, DNS_SERVER_PORT)).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) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) TcpDnsQueryEncoder(io.netty.handler.codec.dns.TcpDnsQueryEncoder) ChannelPipeline(io.netty.channel.ChannelPipeline) DefaultDnsResponse(io.netty.handler.codec.dns.DefaultDnsResponse) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Random(java.util.Random) DefaultDnsQuery(io.netty.handler.codec.dns.DefaultDnsQuery) Bootstrap(io.netty.bootstrap.Bootstrap) 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) SslContext(io.netty.handler.ssl.SslContext) DefaultDnsQuestion(io.netty.handler.codec.dns.DefaultDnsQuestion)

Example 12 with SimpleChannelInboundHandler

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

the class TcpDnsServer method main.

public static void main(String[] args) throws Exception {
    ServerBootstrap bootstrap = new ServerBootstrap().group(new NioEventLoopGroup(1), new NioEventLoopGroup()).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new TcpDnsQueryDecoder(), new TcpDnsResponseEncoder(), new SimpleChannelInboundHandler<DnsQuery>() {

                @Override
                protected void channelRead0(ChannelHandlerContext ctx, DnsQuery msg) throws Exception {
                    DnsQuestion question = msg.recordAt(DnsSection.QUESTION);
                    System.out.println("Query domain: " + question);
                    // always return 192.168.1.1
                    ctx.writeAndFlush(newResponse(msg, question, 600, QUERY_RESULT));
                }

                private DefaultDnsResponse newResponse(DnsQuery query, DnsQuestion question, long ttl, byte[]... addresses) {
                    DefaultDnsResponse response = new DefaultDnsResponse(query.id());
                    response.addRecord(DnsSection.QUESTION, question);
                    for (byte[] address : addresses) {
                        DefaultDnsRawRecord queryAnswer = new DefaultDnsRawRecord(question.name(), DnsRecordType.A, ttl, Unpooled.wrappedBuffer(address));
                        response.addRecord(DnsSection.ANSWER, queryAnswer);
                    }
                    return response;
                }
            });
        }
    });
    final Channel channel = bootstrap.bind(DNS_SERVER_PORT).channel();
    Executors.newSingleThreadScheduledExecutor().schedule(new Runnable() {

        @Override
        public void run() {
            try {
                clientQuery();
                channel.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 1000, TimeUnit.MILLISECONDS);
    channel.closeFuture().sync();
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) LoggingHandler(io.netty.handler.logging.LoggingHandler) 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) DefaultDnsQuestion(io.netty.handler.codec.dns.DefaultDnsQuestion) DnsQuestion(io.netty.handler.codec.dns.DnsQuestion) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DefaultDnsRawRecord(io.netty.handler.codec.dns.DefaultDnsRawRecord) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) DefaultDnsResponse(io.netty.handler.codec.dns.DefaultDnsResponse) TcpDnsQueryDecoder(io.netty.handler.codec.dns.TcpDnsQueryDecoder) DefaultDnsQuery(io.netty.handler.codec.dns.DefaultDnsQuery) DnsQuery(io.netty.handler.codec.dns.DnsQuery) TcpDnsResponseEncoder(io.netty.handler.codec.dns.TcpDnsResponseEncoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 13 with SimpleChannelInboundHandler

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

the class TcpDnsClient method main.

public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                p.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) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) TcpDnsQueryEncoder(io.netty.handler.codec.dns.TcpDnsQueryEncoder) ChannelPipeline(io.netty.channel.ChannelPipeline) DefaultDnsResponse(io.netty.handler.codec.dns.DefaultDnsResponse) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Random(java.util.Random) DefaultDnsQuery(io.netty.handler.codec.dns.DefaultDnsQuery) Bootstrap(io.netty.bootstrap.Bootstrap) 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 14 with SimpleChannelInboundHandler

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

the class DnsClient method main.

public static void main(String[] args) throws Exception {
    InetSocketAddress addr = new InetSocketAddress(DNS_SERVER_HOST, DNS_SERVER_PORT);
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).handler(new ChannelInitializer<DatagramChannel>() {

            @Override
            protected void initChannel(DatagramChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new DatagramDnsQueryEncoder()).addLast(new DatagramDnsResponseDecoder()).addLast(new SimpleChannelInboundHandler<DatagramDnsResponse>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, DatagramDnsResponse msg) {
                        try {
                            handleQueryResp(msg);
                        } finally {
                            ctx.close();
                        }
                    }
                });
            }
        });
        final Channel ch = b.bind(0).sync().channel();
        DnsQuery query = new DatagramDnsQuery(null, addr, 1).setRecord(DnsSection.QUESTION, new DefaultDnsQuestion(QUERY_DOMAIN, DnsRecordType.A));
        ch.writeAndFlush(query).sync();
        boolean succ = ch.closeFuture().await(10, TimeUnit.SECONDS);
        if (!succ) {
            System.err.println("dns query timeout!");
            ch.close().sync();
        }
    } finally {
        group.shutdownGracefully();
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) InetSocketAddress(java.net.InetSocketAddress) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) DatagramChannel(io.netty.channel.socket.DatagramChannel) Channel(io.netty.channel.Channel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) DatagramChannel(io.netty.channel.socket.DatagramChannel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPipeline(io.netty.channel.ChannelPipeline) DatagramDnsQueryEncoder(io.netty.handler.codec.dns.DatagramDnsQueryEncoder) DatagramDnsResponse(io.netty.handler.codec.dns.DatagramDnsResponse) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) DatagramDnsQuery(io.netty.handler.codec.dns.DatagramDnsQuery) Bootstrap(io.netty.bootstrap.Bootstrap) DnsQuery(io.netty.handler.codec.dns.DnsQuery) DatagramDnsQuery(io.netty.handler.codec.dns.DatagramDnsQuery) DatagramDnsResponseDecoder(io.netty.handler.codec.dns.DatagramDnsResponseDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) DefaultDnsQuestion(io.netty.handler.codec.dns.DefaultDnsQuestion)

Example 15 with SimpleChannelInboundHandler

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

the class LocalChannelTest method testNotLeakBuffersWhenCloseByRemotePeer.

@Test
public void testNotLeakBuffersWhenCloseByRemotePeer() throws Exception {
    Bootstrap cb = new Bootstrap();
    ServerBootstrap sb = new ServerBootstrap();
    cb.group(sharedGroup).channel(LocalChannel.class).handler(new SimpleChannelInboundHandler<ByteBuf>() {

        @Override
        public void channelActive(final ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush(ctx.alloc().buffer().writeZero(100));
        }

        @Override
        public void channelRead0(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
        // Just drop the buffer
        }
    });
    sb.group(sharedGroup).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {

        @Override
        public void initChannel(LocalChannel ch) throws Exception {
            ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {

                @Override
                public void channelRead0(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
                    while (buffer.isReadable()) {
                        // Fill the ChannelOutboundBuffer with multiple buffers
                        ctx.write(buffer.readRetainedSlice(1));
                    }
                    // Flush and so transfer the written buffers to the inboundBuffer of the remote peer.
                    // After this point the remote peer is responsible to release all the buffers.
                    ctx.flush();
                    // This close call will trigger the remote peer close as well.
                    ctx.close();
                }
            });
        }
    });
    Channel sc = null;
    LocalChannel cc = null;
    try {
        // Start server
        sc = sb.bind(TEST_ADDRESS).sync().channel();
        // Connect to the server
        cc = (LocalChannel) cb.connect(sc.localAddress()).sync().channel();
        // Close the channel
        closeChannel(cc);
        assertTrue(cc.inboundBuffer.isEmpty());
        closeChannel(sc);
    } finally {
        closeChannel(cc);
        closeChannel(sc);
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) AbstractChannel(io.netty.channel.AbstractChannel) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ConnectException(java.net.ConnectException) ClosedChannelException(java.nio.channels.ClosedChannelException) 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