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:edu.upennlib.redirect.Redirect.java

License:Apache License

@Override
public void run() {
    // Configure the bootstrap.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {// w ww.  j av  a 2 s.  c om
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new RedirectInitializer(validHosts, redirectPrefix))
                .childOption(ChannelOption.AUTO_READ, true).bind(listenInterface, listenPort).sync().channel()
                .closeFuture().sync();
    } catch (InterruptedException ex) {
        throw new RuntimeException(ex);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:io.hekate.network.netty.NettyServer.java

License:Apache License

private void setOpts(ServerBootstrap boot) {
    setUserOpt(boot, ChannelOption.SO_BACKLOG, soBacklog);
    setUserOpt(boot, ChannelOption.SO_RCVBUF, soReceiveBufferSize);
    setUserOpt(boot, ChannelOption.SO_REUSEADDR, soReuseAddress);

    if (!autoAccept) {
        setUserOpt(boot, ChannelOption.AUTO_READ, false);
    }/* w w  w  . ja v a  2s.co m*/
}

From source file:io.reactivesocket.netty.tcp.client.ClientTcpDuplexConnection.java

License:Apache License

public static Publisher<ClientTcpDuplexConnection> create(SocketAddress address,
        EventLoopGroup eventLoopGroup) {
    return s -> {
        CopyOnWriteArrayList<Observer<Frame>> subjects = new CopyOnWriteArrayList<>();
        ReactiveSocketClientHandler clientHandler = new ReactiveSocketClientHandler(subjects);
        Bootstrap bootstrap = new Bootstrap();
        ChannelFuture connect = bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.AUTO_READ, true).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override/*w  ww  .j a v a 2  s.  c  om*/
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE >> 1, 0,
                                BitUtil.SIZE_OF_INT, -1 * BitUtil.SIZE_OF_INT, 0), clientHandler);
                    }
                }).connect(address);

        connect.addListener(connectFuture -> {
            if (connectFuture.isSuccess()) {
                Channel ch = connect.channel();
                s.onNext(new ClientTcpDuplexConnection(ch, subjects));
                s.onComplete();
            } else {
                s.onError(connectFuture.cause());
            }
        });
    };
}

From source file:io.urmia.api.Main.java

License:Open Source License

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

    boolean autoRegister = ArgumentParseUtil.isAutoRegister(args);
    String zkURL = ArgumentParseUtil.getZooKeeperURL(args);

    log.info("starting with zk at: {}, auto register: {}", zkURL, autoRegister);

    ns = new ZkNamingServiceImpl(zkURL, AZ);

    Optional<ServiceInstance<NodeType>> meOpt = ns.whoAmI(NodeType.MDS, autoRegister);

    if (!meOpt.isPresent()) {
        System.err.println("unable to find my instance. use auto register or cli-admin to add my node");
        System.exit(1);/*from ww  w .j  ava2 s.com*/
        return;
    }

    Runtime.getRuntime().addShutdownHook(new ShutdownHook());

    uuid = new RandomUuidImpl();

    //Properties properties = parseArguments(args);
    EventLoopGroup bossGroup = new NioEventLoopGroup(/*1*/);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        me = meOpt.get();

        log.info("my service instance: {}", me);

        BoneCPConfig boneCPConfig = getBoneCPConfig(ns);

        ns.register(me);

        int port = me.getPort();

        JdbcPool pool = new JdbcPool.BoneCPJdbcPool(boneCPConfig);

        MetadataRepository repository = new PsqlMetadataRepositoryImpl(pool);

        mds = new DefaultMetadataServiceImpl(repository);

        // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#14.0
        ServerBootstrap b = new ServerBootstrap();

        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.AUTO_READ, false)
                .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true))
                .childHandler(new HttpUploadServerInitializer());

        Channel ch = b.bind(port).sync().channel();
        log.info("object metadata API server (MDS) at port: {}", port);

        ch.closeFuture().sync();
    } finally {
        ns.deregister(me);
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:io.urmia.job.Main.java

License:Open Source License

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

    boolean autoRegister = ArgumentParseUtil.isAutoRegister(args);
    String zkURL = ArgumentParseUtil.getZooKeeperURL(args);

    log.info("starting with zk at: {}, auto register: {}", zkURL, autoRegister);

    ns = new ZkNamingServiceImpl(zkURL, AZ);

    Optional<ServiceInstance<NodeType>> meOpt = ns.whoAmI(NodeType.JDS, autoRegister);

    if (!meOpt.isPresent()) {
        System.err.println("unable to find my instance. use auto register or cli-admin to add my node");
        System.exit(1);//www. jav a  2s . c  o  m
        return;
    }

    Runtime.getRuntime().addShutdownHook(new ShutdownHook());

    EventLoopGroup bossGroup = new NioEventLoopGroup(/*1*/);

    try {
        me = meOpt.get();

        log.info("my service instance: {}", me);

        BoneCPConfig boneCPConfig = getBoneCPConfig(ns);

        ns.register(me);

        int port = me.getPort();

        CuratorFramework client = CuratorFrameworkFactory.newClient(zkURL,
                new ExponentialBackoffRetry(1000, 3));
        client.start();

        JdbcPool pool = new JdbcPool.BoneCPJdbcPool(boneCPConfig);

        MetadataRepository repository = new PsqlMetadataRepositoryImpl(pool);

        MetadataService mds = new DefaultMetadataServiceImpl(repository);

        ServerBootstrap b = new ServerBootstrap();

        b.group(bossGroup).channel(NioServerSocketChannel.class).childOption(ChannelOption.AUTO_READ, true)
                .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator())
                .childHandler(new JobApiServerInitializer(client, mds));

        Channel ch = b.bind(port).sync().channel();
        log.info("Job API Server (JDS) at port: {}", port);

        ch.closeFuture().sync();
    } finally {
        ns.deregister(me);
        bossGroup.shutdownGracefully();
        //workerGroup.shutdownGracefully();
    }
}

From source file:io.urmia.proxy.HttpProxyFrontendHandler.java

License:Open Source License

private Channel openOutboundChannel(final ChannelHandlerContext ctx, String remoteHost, int remotePort,
        final int index) {

    log.info("proxy opening outbound channel to({}): {}:{}", index, remoteHost, remotePort);

    Bootstrap b = new Bootstrap();
    b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
            .handler(new HttpProxyBackendInitializer(ctx, index, directWriteBack))
            .option(ChannelOption.AUTO_READ, false);

    ChannelFuture f = b.connect(remoteHost, remotePort);
    Channel outboundChannel = f.channel();
    f.addListener(new GenericFutureListener<ChannelFuture>() {
        @Override//from w  w w . j a  va2s  .  c om
        public void operationComplete(ChannelFuture futureC) throws Exception {
            if (futureC.isSuccess()) {
                futureC.channel().writeAndFlush(initHttpRequest)
                        .addListener(new GenericFutureListener<ChannelFuture>() {
                            @Override
                            public void operationComplete(ChannelFuture futureW) throws Exception {
                                if (futureW.isSuccess())
                                    onSuccessfulWrite(ctx, index);
                                else {
                                    log.info("unable to write http request: {}", futureW.cause());
                                    ctx.fireUserEventTriggered(new ProxyUserEvent(OUTBOUND_ERROR, index));
                                }
                            }
                        });
            } else {
                ctx.fireUserEventTriggered(new ProxyUserEvent(OUTBOUND_ERROR, index));
            }
        }
    });

    return outboundChannel;
}

From source file:io.urmia.st.Main.java

License:Open Source License

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

    final int port;
    final String base;

    boolean autoRegister = ArgumentParseUtil.isAutoRegister(args);
    String zkURL = ArgumentParseUtil.getZooKeeperURL(args);

    log.info("starting with zk at: {}, auto register: {}", zkURL, autoRegister);

    ns = new ZkNamingServiceImpl(zkURL, AZ);

    Optional<ServiceInstance<NodeType>> meOpt = ns.whoAmI(NodeType.ODS, autoRegister);

    if (!meOpt.isPresent()) {
        System.err.println("unable to find my instance. use auto register or cli-admin to add my node");
        System.exit(1);/*from ww w . j  a va 2 s  .  co m*/
        return;
    }

    Runtime.getRuntime().addShutdownHook(new ShutdownHook());

    EventLoopGroup bossGroup = new NioEventLoopGroup(/*1*/);
    //EventLoopGroup bossGroup = new EpollEventLoopGroup(1);
    //EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        me = meOpt.get();

        log.info("my service instance: {}", me);

        ns.register(me);

        base = me.getUriSpec().getParts().get(0).getValue();
        port = me.getPort();

        if (!(new File(base).isDirectory())) {
            System.err.println("base in not directory: " + base);
            return;
        }

        int nHeapArena = 1;
        int nDirectArena = 1;
        int pageSize = /*8192*/4096;
        int maxOrder = 1;

        // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#14.0
        ServerBootstrap b = new ServerBootstrap();

        b.group(bossGroup).channel(NioServerSocketChannel.class).childOption(ChannelOption.AUTO_READ, false)
                .childOption(ChannelOption.ALLOCATOR,
                        new PooledByteBufAllocator(true, nHeapArena, nDirectArena, pageSize, maxOrder))
                .childHandler(new HttpUploadServerInitializer(base));

        Channel ch = b.bind(port).sync().channel();
        log.info("object storage Server (ODS) at port: {}", port);

        System.err.println("starting ODS " + me.getId() + " on port: " + port + ", base: " + base);

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        //workerGroup.shutdownGracefully();
    }
}

From source file:malcolm.HttpProxyFrontendHandler.java

License:Apache License

private Bootstrap backendChannelBootstap(final Channel frontendChannel) {
    return new Bootstrap().group(frontendChannel.eventLoop()).channel(NioSocketChannel.class)
            .handler(new HttpProxyBackendInitializer(frontendChannel)).option(ChannelOption.AUTO_READ, false);
}

From source file:me.bigteddy98.mcproxy.Main.java

License:Open Source License

public void run() throws Exception {
    ProxyLogger.info("Starting " + NAME + " version " + VERSION + " developed by " + AUTHOR + "!");
    ProxyLogger.info(//from w  w  w  . j av a 2s. c om
            "Starting server process using commandline " + Arrays.asList(processBuilder).toString() + "...");
    ProcessBuilder builder = new ProcessBuilder(processBuilder);
    builder.redirectErrorStream(true);
    this.serverProcess = builder.start();
    this.processPrintWriter = new PrintWriter(this.serverProcess.getOutputStream());
    ProxyLogger.info("Server process started.");

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

        @Override
        public void run() {
            serverProcess.destroy();
        }
    }));

    new Thread(new Runnable() {

        @Override
        public void run() {
            try (InputStream r = serverProcess.getInputStream()) {
                StringBuilder tmp = new StringBuilder();
                byte[] consoleOutput = new byte[1024];
                int read;
                while ((read = r.read(consoleOutput)) != -1) {
                    String consoleLog = new String(consoleOutput, 0, read);
                    String[] c = consoleLog.split("\n", -1);
                    if (c.length != 0) {
                        if (c.length == 1) {
                            tmp.append(c[0]);
                        } else {
                            for (int i = 0; i < c.length - 1; i++) {
                                tmp.append(c[i]);
                                ProxyLogger.info(tmp.toString());
                                tmp.setLength(0);
                            }
                            tmp.append(c[c.length - 1]);
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            ProxyLogger.warn("Server thread ended!");
            System.exit(0);
        }
    }, "Server Output Reader").start();

    new Thread(new Runnable() {

        @Override
        public void run() {
            try (Scanner in = new Scanner(System.in)) {
                while (in.hasNextLine()) {
                    String newLine = in.nextLine();
                    executeCommand(newLine);
                }
            }
            ProxyLogger.warn("COMMAND LOOP ENDED, this shouldn't happen!");
        }
    }, "CommandReader").start();

    final ThreadGroup nettyListeners = new ThreadGroup(Thread.currentThread().getThreadGroup(),
            "Netty Listeners");
    new Thread(nettyListeners, new Runnable() {

        @Override
        public void run() {
            ProxyLogger.info("Started Netty Server at port " + fromPort + "...");
            final ThreadGroup group = new ThreadGroup(nettyListeners, "Listener-" + toPort);
            EventLoopGroup bossGroup = new NioEventLoopGroup(MAX_NETTY_BOSS_THREADS, new ThreadFactory() {

                private int threadCount = 0;
                private String newName = group.getName() + "\\boss";

                @Override
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(group, r, newName + "\\" + threadCount++);
                    t.setPriority(Thread.NORM_PRIORITY - 1);
                    t.setDaemon(true);
                    return t;
                }
            });
            EventLoopGroup workerGroup = new NioEventLoopGroup(MAX_NETTY_WORKER_THREADS, new ThreadFactory() {

                private int threadCount = 0;
                private String newName = group.getName() + "\\worker";

                @Override
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(group, r, newName + "\\" + threadCount++);
                    t.setPriority(Thread.NORM_PRIORITY - 1);
                    t.setDaemon(true);
                    return t;
                }
            });
            try {
                ServerBootstrap bootstrab = new ServerBootstrap();
                bootstrab.group(bossGroup, workerGroup);
                bootstrab.channel(NioServerSocketChannel.class);
                bootstrab.childHandler(new ClientboundConnectionInitializer("localhost", toPort));
                bootstrab.childOption(ChannelOption.AUTO_READ, false);
                bootstrab.bind(fromPort).sync().channel().closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }
    }).start();
}

From source file:me.bigteddy98.mcproxy.protocol.handlers.ClientSideHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    incomingChannel = ctx.channel();/*  w w w .ja  v  a2 s  . c  o m*/
    networkManager.clientsidePipeline = ctx.pipeline();

    Bootstrap bootstrab = new Bootstrap();
    bootstrab.group(incomingChannel.eventLoop());
    bootstrab.channel(ctx.channel().getClass());
    bootstrab.handler(serverboundConnectionInitializer = new ServerboundConnectionInitializer(networkManager,
            incomingChannel));
    bootstrab.option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = bootstrab.connect(hostname, port);

    outgoingChannel = f.channel();
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                incomingChannel.read();
            } else {
                incomingChannel.close();
            }
        }
    });
}