Example usage for io.netty.channel ChannelOption AUTO_READ

List of usage examples for io.netty.channel ChannelOption AUTO_READ

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption AUTO_READ.

Prototype

ChannelOption AUTO_READ

To view the source code for io.netty.channel ChannelOption AUTO_READ.

Click Source Link

Usage

From source file:com.xx_dev.apn.proxy.ApnProxyUserAgentForwardHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception {

    final Channel uaChannel = uaChannelCtx.channel();

    final ApnProxyRemote apnProxyRemote = uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get()
            .getRemote();//from  w w w.  j av a 2  s  .  c  o  m

    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;

        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());

        if (remoteChannel != null && remoteChannel.isActive()) {
            LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                    "Use old remote channel");
            HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote);
            remoteChannel.writeAndFlush(request);
        } else {
            LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                    "Create new remote channel");

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(uaChannel.eventLoop()).channel(NioSocketChannel.class)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .option(ChannelOption.AUTO_READ, false)
                    .handler(new ApnProxyRemoteForwardChannelInitializer(uaChannel, this));

            // set local address
            if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) {
                bootstrap.localAddress(new InetSocketAddress(
                        (ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0));
            }

            ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getRemoteHost(),
                    apnProxyRemote.getRemotePort());

            remoteChannel = remoteConnectFuture.channel();
            remoteChannelMap.put(apnProxyRemote.getRemoteAddr(), remoteChannel);

            remoteConnectFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        future.channel().write(constructRequestForProxy((HttpRequest) msg, apnProxyRemote));

                        for (HttpContent hc : httpContentBuffer) {
                            future.channel().writeAndFlush(hc);

                            if (hc instanceof LastHttpContent) {
                                future.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future)
                                                    throws Exception {
                                                if (future.isSuccess()) {
                                                    future.channel().read();
                                                }

                                            }
                                        });
                            }
                        }
                        httpContentBuffer.clear();
                    } else {
                        LoggerUtil.error(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                                "Remote channel create fail");

                        // send error response
                        String errorMsg = "remote connect to "
                                + uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote()
                                        .getRemoteAddr()
                                + " fail";
                        HttpMessage errorResponseMsg = HttpErrorUtil
                                .buildHttpErrorMessage(HttpResponseStatus.INTERNAL_SERVER_ERROR, errorMsg);
                        uaChannel.writeAndFlush(errorResponseMsg);
                        httpContentBuffer.clear();

                        future.channel().close();
                    }
                }
            });

        }
        ReferenceCountUtil.release(msg);
    } else {
        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());

        HttpContent hc = ((HttpContent) msg);
        //hc.retain();

        //HttpContent _hc = hc.copy();

        if (remoteChannel != null && remoteChannel.isActive()) {
            remoteChannel.writeAndFlush(hc);

            if (hc instanceof LastHttpContent) {
                remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            future.channel().read();
                        }

                    }
                });
            }
        } else {
            httpContentBuffer.add(hc);
        }
    }

}

From source file:com.xx_dev.apn.proxy.ApnProxyUserAgentTunnelHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception {

    if (msg instanceof HttpRequest) {
        final HttpRequest httpRequest = (HttpRequest) msg;

        //Channel uaChannel = uaChannelCtx.channel();

        // connect remote
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.AUTO_READ, false)
                .handler(new ApnProxyTunnelChannelInitializer(uaChannelCtx.channel()));

        final ApnProxyRemote apnProxyRemote = uaChannelCtx.channel()
                .attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();

        // set local address
        if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) {
            bootstrap.localAddress(new InetSocketAddress(
                    (ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0));
        }/*w  ww . j  av  a 2 s  .  c  o m*/

        bootstrap.connect(apnProxyRemote.getRemoteHost(), apnProxyRemote.getRemotePort())
                .addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(final ChannelFuture future1) throws Exception {
                        if (future1.isSuccess()) {
                            if (apnProxyRemote.isAppleyRemoteRule()) {
                                uaChannelCtx.pipeline().remove("codec");
                                uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME);
                                uaChannelCtx.pipeline().remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME);

                                // add relay handler
                                uaChannelCtx.pipeline()
                                        .addLast(new ApnProxyRelayHandler("UA --> Remote", future1.channel()));

                                future1.channel()
                                        .writeAndFlush(Unpooled.copiedBuffer(
                                                constructConnectRequestForProxy(httpRequest, apnProxyRemote),
                                                CharsetUtil.UTF_8))
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future2)
                                                    throws Exception {
                                                if (!future2.channel().config()
                                                        .getOption(ChannelOption.AUTO_READ)) {
                                                    future2.channel().read();
                                                }
                                            }
                                        });

                            } else {
                                HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse(
                                        HttpVersion.HTTP_1_1,
                                        new HttpResponseStatus(200, "Connection established"));
                                uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse)
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future2)
                                                    throws Exception {
                                                // remove handlers
                                                uaChannelCtx.pipeline().remove("codec");
                                                uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME);
                                                uaChannelCtx.pipeline()
                                                        .remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME);

                                                // add relay handler
                                                uaChannelCtx.pipeline()
                                                        .addLast(new ApnProxyRelayHandler(
                                                                "UA --> " + apnProxyRemote.getRemoteAddr(),
                                                                future1.channel()));
                                            }

                                        });
                            }

                        } else {
                            if (uaChannelCtx.channel().isActive()) {
                                uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(ChannelFutureListener.CLOSE);
                            }
                        }
                    }
                });

    }
    ReferenceCountUtil.release(msg);
}

From source file:com.xx_dev.apn.socks.local.PortForwardProxy.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {//w  w w .ja  v  a  2 s  .c  o  m
        ServerBootstrap b = new ServerBootstrap();
        ChannelFuture bindFuture = b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new PortForwardProxyFrontendInitializer(LocalConfig.ins().getRemoteHost(),
                        LocalConfig.ins().getRemotePort()))
                .childOption(ChannelOption.AUTO_READ, false).bind(LocalConfig.ins().getLocalPort());

        bindFuture.sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

}

From source file:com.xx_dev.apn.socks.local.PortForwardProxyFrontendHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass())
            .handler(new PortForwardProxyBackendInitializer(inboundChannel))
            .option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(remoteHost, remotePort);
    outboundChannel = f.channel();/*from   ww w  .  ja va  2s .c  o  m*/
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                // connection complete start to read first data
                logger.info("C: " + remoteHost + ":" + remotePort + ", T");
                inboundChannel.read();
            } else {
                logger.info("C: " + remoteHost + ":" + remotePort + ", F");
                inboundChannel.close();
            }
        }
    });
}

From source file:com.xx_dev.port_forwared.HexDumpProxy.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    List<HexDumpForwardRule> ruleList = new ArrayList<HexDumpForwardRule>();
    HexDumpForwardRule r3 = new HexDumpForwardRule(9000, "imap.gmail.com", 993, true);
    ruleList.add(r3);/* w  w w .ja v a2s.c om*/
    HexDumpForwardRule r4 = new HexDumpForwardRule(9001, "smtp.gmail.com", 465, true);
    ruleList.add(r4);

    List<ChannelFuture> bindFutureList = new ArrayList<ChannelFuture>();

    try {
        for (HexDumpForwardRule r : ruleList) {

            ServerBootstrap b = new ServerBootstrap();
            ChannelFuture bindFuture = b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler("BYTE_LOGGER", LogLevel.DEBUG))
                    .childHandler(
                            new HexDumpProxyInitializer(r.getRemoteHost(), r.getRemotePort(), r.isRemoteSsl()))
                    .childOption(ChannelOption.AUTO_READ, false).bind(r.getLocalPort());

            bindFutureList.add(bindFuture);

        }
        for (ChannelFuture f : bindFutureList) {
            f.sync().channel().closeFuture().sync();
        }
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

}

From source file:com.xx_dev.port_forwared.HexDumpProxyFrontendHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass())
            .handler(new HexDumpProxyBackendInitializer(inboundChannel, remoteSsl))
            .option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(remoteHost, remotePort);
    outboundChannel = f.channel();//  ww w .j  ava2 s  .co m
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });
}

From source file:de.jackwhite20.apex.tcp.ApexSocket.java

License:Open Source License

@Override
public Channel bootstrap(EventLoopGroup bossGroup, EventLoopGroup workerGroup, String ip, int port, int backlog,
        int readTimeout, int writeTimeout) throws Exception {

    logger.info("Bootstrapping socket server");

    ServerBootstrap bootstrap = new ServerBootstrap().group(bossGroup, workerGroup)
            .channel(PipelineUtils.getServerChannel())
            .childHandler(new ApexSocketChannelInitializer(readTimeout, writeTimeout))
            .childOption(ChannelOption.AUTO_READ, false);

    if (PipelineUtils.isEpoll()) {
        bootstrap.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);

        logger.debug("Epoll mode is now level triggered");
    }//from  w  w w. j a va 2  s.com

    return bootstrap.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_BACKLOG, backlog)
            .bind(ip, port).sync().channel();
}

From source file:de.jackwhite20.apex.tcp.pipeline.handler.SocketUpstreamHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) {

    final Channel inboundChannel = ctx.channel();

    Bootstrap b = new Bootstrap().group(inboundChannel.eventLoop()).channel(PipelineUtils.getChannel())
            .handler(new SocketDownstreamHandler(inboundChannel)).option(ChannelOption.TCP_NODELAY, true)
            // No initial connection should take longer than 4 seconds
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, BackendInfo.DEFAULT_TCP_TIMEOUT)
            .option(ChannelOption.AUTO_READ, false);

    ChannelFuture f = b.connect(backendInfo.getHost(), backendInfo.getPort());
    downstreamChannel = f.channel();//www  .j a va2 s .c  o  m
    f.addListener((ChannelFutureListener) future -> {

        if (future.isSuccess()) {
            inboundChannel.read();
        } else {
            inboundChannel.close();
        }
    });

    // Add the channel to the channel group
    Apex.getChannelGroup().add(inboundChannel);
}

From source file:de.jackwhite20.comix.Comix.java

License:Open Source License

public void start() {
    System.setProperty("java.net.preferIPv4Stack", "true");

    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED);

    AnsiConsole.systemInstall();//  w w  w . jav a 2s .com

    LogManager.getLogManager().reset();

    logger = new ComixLogger(consoleReader);

    logger.log(Level.INFO, "Comix", "------ Comix v.0.1 ------");

    loadConfig();

    logger.log(Level.INFO, "Load-Balancer", (targets.size() > 0) ? "Targets:" : "No Target Servers found!");
    targets.forEach(t -> logger.log(Level.INFO, "Load-Balancer",
            t.getName() + " - " + t.getHost() + ":" + t.getPort()));

    logger.log(Level.INFO, "Commands", "Registering commands...");

    registerCommands();

    logger.log(Level.INFO, "Comix", "Starting Comix on " + balancerHost + ":" + balancerPort + "...");

    balancingStrategy = new RoundRobinBalancingStrategy(targets);

    new Timer("CheckTargets").scheduleAtFixedRate(new CheckTargets(balancingStrategy), 0,
            TimeUnit.SECONDS.toMillis(comixConfig.getCheckTime()));

    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup(comixConfig.getThreads());

    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_BACKLOG, comixConfig.getBacklog())
                .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.AUTO_READ, false).childOption(ChannelOption.SO_TIMEOUT, 4000)
                .childHandler(new ComixChannelInitializer());

        ChannelFuture f = bootstrap.bind(comixConfig.getPort()).sync();

        reload();

        logger.log(Level.INFO, "Comix", "Comix is started!");

        f.channel().closeFuture().sync();

        running = false;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        shutdown();
    }
}

From source file:de.jackwhite20.comix.handler.UpstreamHandler.java

License:Open Source License

public void connectDownstream(ByteBuf initPacket) {
    InetSocketAddress address = (InetSocketAddress) upstreamChannel.remoteAddress();
    TargetData target = this.strategy.selectTarget(address.getHostName(), address.getPort());

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(upstreamChannel.eventLoop()).channel(upstreamChannel.getClass())
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.AUTO_READ, false)
            .option(ChannelOption.SO_TIMEOUT, 5000).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000)
            .handler(downstreamHandler = new DownstreamHandler(client, upstreamChannel));

    ChannelFuture f = bootstrap.connect(target.getHost(), target.getPort());
    downstreamChannel = f.channel();//from  w  w w  . j  a v a 2s  . c o m

    initialPackets.add(initPacket);

    f.addListener((future) -> {
        if (future.isSuccess()) {
            downstreamConnected = true;

            for (ByteBuf packet : initialPackets) {
                downstreamChannel.writeAndFlush(packet);
            }

            Comix.getLogger().log(Level.INFO, "Proxy",
                    "[" + client.getName() + "] <-> [Comix] <-> [" + target.getName() + "] tunneled");
        } else {
            upstreamChannel.close();
        }
    });
}