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:NettyHttpListner.java

License:Apache License

public void start() {

    System.out.println("Starting the server...");
    System.out.println("Starting Inbound Http Listner on Port " + this.port);

    // Configure SSL.
    SslContext sslCtx = null;//from  w  w  w. ja  v  a 2s. c o  m
    if (SSL) {
        try {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (CertificateException ex) {
            Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SSLException ex) {
            Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    commonEventLoopGroup = new NioEventLoopGroup(bossGroupSize);
    //        bossGroup = new NioEventLoopGroup(bossGroupSize);
    //        workerGroup = new NioEventLoopGroup(workerGroupSize);

    try {
        ServerBootstrap b = new ServerBootstrap();

        //            b.commonEventLoopGroup(bossGroup, workerGroup)
        b.group(commonEventLoopGroup).channel(NioServerSocketChannel.class)
                .childHandler(
                        new NettyHttpTransportHandlerInitializer(HOST, HOST_PORT, maxConnectionsQueued, sslCtx))
                .childOption(ChannelOption.AUTO_READ, false);

        b.option(ChannelOption.TCP_NODELAY, true);
        b.childOption(ChannelOption.TCP_NODELAY, true);

        b.option(ChannelOption.SO_BACKLOG, maxConnectionsQueued);

        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);

        b.option(ChannelOption.SO_SNDBUF, 1048576);
        b.option(ChannelOption.SO_RCVBUF, 1048576);
        b.childOption(ChannelOption.SO_RCVBUF, 1048576);
        b.childOption(ChannelOption.SO_SNDBUF, 1048576);

        b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

        Channel ch = null;
        try {
            ch = b.bind(port).sync().channel();
            ch.closeFuture().sync();
            System.out.println("Inbound Listner Started");
        } catch (InterruptedException e) {
            System.out.println("Exception caught");
        }
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:NettyHttpTransportSourceHandler.java

License:Apache License

/**
 * activating registered handler to accept events.
 *
 * @param ctx// ww w  . j a  va  2s  .c om
 * @throws Exception
 */
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    final Channel inboundChannel = ctx.channel();

    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass());
    b.handler(new NettyTargetHandlerInitilizer(inboundChannel)).option(ChannelOption.AUTO_READ, false);

    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);

    b.option(ChannelOption.SO_SNDBUF, 1048576);
    b.option(ChannelOption.SO_RCVBUF, 1048576);

    ChannelFuture f = b.connect(NettyHttpListner.HOST, NettyHttpListner.HOST_PORT);

    outboundChannel = f.channel();
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            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:com.allanbank.mongodb.netty.NettyTransport.java

License:Apache License

/**
 * Creates a new NettySocketConnection./*from   w w w  . j  a  va  2 s .c o  m*/
 *
 * @param server
 *            The MongoDB server to connect to.
 * @param config
 *            The configuration for the Connection to the MongoDB server.
 * @param encoderCache
 *            Cache used for encoding strings.
 * @param decoderCache
 *            Cache used for decoding strings.
 * @param responseListener
 *            The listener for the status of the transport/connection.
 * @param bootstrap
 *            The seeded bootstrap for creating the {@link Channel}.
 *
 * @throws IOException
 *             On a failure connecting to the MongoDB server.
 */
public NettyTransport(final Server server, final MongoClientConfiguration config,
        final StringEncoderCache encoderCache, final StringDecoderCache decoderCache,
        final TransportResponseListener responseListener, final Bootstrap bootstrap) throws IOException {

    myEncoderCache = encoderCache;

    // These are critical settings for performance/function.
    bootstrap.option(ChannelOption.TCP_NODELAY, Boolean.TRUE);
    bootstrap.option(ChannelOption.AUTO_READ, Boolean.TRUE);

    bootstrap.handler(new NettyChannelInit(config, decoderCache, responseListener));

    Channel channel = null;
    final Iterator<InetSocketAddress> addrIter = server.getAddresses().iterator();
    IOException error = null;
    while (addrIter.hasNext() && (channel == null)) {
        final InetSocketAddress address = addrIter.next();
        try {
            channel = bootstrap.connect(address).await().channel();
        } catch (final InterruptedException e) {
            error = new IOException("Failed to wait for the connection to complete.", e);
        } catch (final RuntimeException e) {
            error = new IOException("Failed to create a connection to '" + address + "'.", e);
        }
    }

    if (channel != null) {
        myChannel = channel;
    } else if (error != null) {
        throw error;
    } else {
        throw new IOException("Failed to create a connection to the server: " + server.getAddresses());
    }
}

From source file:com.ccompass.netty.proxy.Proxy.java

License:Apache License

public static void main(String[] args) throws Exception {
    ProxyConfig.loadConfig();/* w w w  .  j a  v  a2  s .com*/
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    checkOtherChannel(ProxyConfig.config.checktimes);
    //?grops
    for (int i = 0; i < ProxyConfig.config.branchList.size(); i++) {
        ChannelGroup group = new DefaultChannelGroup("server-group", null);
        NettyClient.sinkGroups.add(group);
    }
    //????
    if (ProxyConfig.config.branchNumbers > 0) {
        List<List<Channel>> list = new ArrayList();
        for (int i = 0; i < ProxyConfig.config.branchList.size(); i++) {
            List<Channel> channels = new ArrayList<Channel>();
            list.add(channels);
        }
        NettyClient.setSinkChannels(list);
    }
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                //    .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ProxyInitializer(ProxyConfig.config.mainIP, ProxyConfig.config.mainPort))
                .childOption(ChannelOption.AUTO_READ, false).bind(ProxyConfig.config.proxyPort).sync().channel()
                .closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.chenyang.proxy.http.HttpRelayHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    if (!ctx.channel().config().getOption(ChannelOption.AUTO_READ)) {
        ctx.read();/*from   w ww.j  a v a 2s  . c  o  m*/
    }
}

From source file:com.chenyang.proxy.http.HttpRelayHandler.java

License:Apache License

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

    if (relayChannel.isActive()) {
        relayChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
            @Override//  w  w w .j  a  va2s .  c  o m
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!ctx.channel().config().getOption(ChannelOption.AUTO_READ)) {
                    ctx.read();
                }
            }
        });
    } else {
        ReferenceCountUtil.release(msg);
    }

}

From source file:com.chenyang.proxy.http.HttpUserAgentForwardHandler.java

License:Apache License

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

    final Channel uaChannel = uaChannelCtx.channel();

    final HttpRemote apnProxyRemote = uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();

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

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

        if (remoteChannel != null && remoteChannel.isActive()) {
            HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote);
            remoteChannel.writeAndFlush(request);
        } else {/*from  ww w .ja v  a  2 s.  c  o m*/

            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 HttpRemoteForwardChannelInitializer(uaChannel, this));

            ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getInetSocketAddress(),
                    new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0));
            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 {
                        HttpErrorUtil.writeAndFlush(uaChannel, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                        httpContentBuffer.clear();
                        future.channel().close();
                    }
                }
            });

        }
        ReferenceCountUtil.release(msg);
    } else {
        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());
        HttpContent hc = ((HttpContent) msg);
        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.chenyang.proxy.http.HttpUserAgentTunnelHandler.java

License:Apache License

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

    if (msg instanceof HttpRequest) {
        // 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 HttpTunnelChannelInitializer(uaChannelCtx.channel()));

        final HttpRemote apnProxyRemote = uaChannelCtx.channel().attr(HttpConnectionAttribute.ATTRIBUTE_KEY)
                .get().getRemote();/*  w w w  .  ja v a 2s. co  m*/

        bootstrap
                .connect(apnProxyRemote.getInetSocketAddress(),
                        new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0))
                .addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(final ChannelFuture future1) throws Exception {
                        if (future1.isSuccess()) {
                            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(HttpPreHandler.HANDLER_NAME);
                                            uaChannelCtx.pipeline()
                                                    .remove(HttpUserAgentTunnelHandler.HANDLER_NAME);

                                            uaChannelCtx.pipeline()
                                                    .addLast(new HttpRelayHandler(
                                                            "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.flysoloing.learning.network.netty.proxy.HexDumpProxy.java

License:Apache License

public static void main(String[] args) throws Exception {
    System.err.println("Proxying *:" + LOCAL_PORT + " to " + REMOTE_HOST + ':' + REMOTE_PORT + " ...");

    // Configure the bootstrap.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from w  w  w .  j  a  v  a 2 s  .  c o  m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new HexDumpProxyInitializer(REMOTE_HOST, REMOTE_PORT))
                .childOption(ChannelOption.AUTO_READ, false).bind(LOCAL_PORT).sync().channel().closeFuture()
                .sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.flysoloing.learning.network.netty.proxy.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 HexDumpProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(remoteHost, remotePort);
    outboundChannel = f.channel();/*from   w  w  w .j  a  v a  2  s . c  o m*/
    f.addListener(new ChannelFutureListener() {
        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();
            }
        }
    });
}