Example usage for io.netty.channel ChannelOption SO_KEEPALIVE

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

Introduction

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

Prototype

ChannelOption SO_KEEPALIVE

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

Click Source Link

Usage

From source file:com.sheldon.javaPrj.netty.DiscardServer.java

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//  www  .ja  v a 2  s . com
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new DiscardServerHandler());
                    }

                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture f = b.bind(port).sync();

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

    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:com.sheldon.javaPrj.netty.FileClient.java

public void start() {
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/* w ww . j a v a  2 s  .  c  o m*/
        Bootstrap b = new Bootstrap();
        b.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChunkedWriteHandler(), new FileClientHandler());
                    }

                });

        ChannelFuture f = b.connect("localhost", port).sync();

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

    } catch (InterruptedException ex) {
        Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        workerGroup.shutdownGracefully();
    }

}

From source file:com.sheldon.javaPrj.netty.FileServer.java

public void start() {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//  ww w .  ja va 2 s  .  com
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new FileServerHandler());
                    }

                });

        ChannelFuture f = b.bind(port).sync();

        System.out.println("server start");

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

        System.out.println("server down");

    } catch (InterruptedException ex) {
        Logger.getLogger(FileServer.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}

From source file:com.sheldon.javaPrj.netty.TimeClient.java

public static void main(String args[]) throws InterruptedException {
    String host = args.length > 0 ? args[0] : "localhost";
    int port = Integer.parseInt(args.length > 1 ? args[1] : "8080");

    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {//  www. ja  v a2  s. c o m
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new TimeClientHandler());
            }
        });

        ChannelFuture f = b.connect(host, port).sync();

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

From source file:com.sheldon.javaPrj.netty.TimeServer.java

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from ww  w.j a v a  2s. co m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new TimeServerHandler());
                    }

                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture f = b.bind(port).sync();

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

    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:com.smoketurner.packet.application.config.NettyConfiguration.java

License:Apache License

@JsonIgnore
public ChannelFuture build(@Nonnull final Environment environment, @Nonnull final Uploader uploader,
        @Nonnull final Size maxUploadSize) throws SSLException, CertificateException {

    // Configure SSL
    final SslContext sslCtx;
    if (ssl) {/*  ww w.jav  a2  s.  co  m*/
        if (selfSignedCert) {
            final SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = SslContextBuilder.forServer(new File(keyCertChainFile), new File(keyFile)).build();
        }
    } else {
        sslCtx = null;
    }

    final UploadInitializer initializer = new UploadInitializer(sslCtx, uploader, maxLength.toBytes(),
            maxUploadSize.toBytes());

    final EventLoopGroup bossGroup;
    final EventLoopGroup workerGroup;
    if (Epoll.isAvailable()) {
        LOGGER.info("Using epoll event loop");
        bossGroup = new EpollEventLoopGroup(1);
        workerGroup = new EpollEventLoopGroup();
    } else {
        LOGGER.info("Using NIO event loop");
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
    }

    environment.lifecycle().manage(new EventLoopGroupManager(bossGroup));
    environment.lifecycle().manage(new EventLoopGroupManager(workerGroup));

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).handler(new LoggingHandler(LogLevel.INFO))
            .option(ChannelOption.SO_BACKLOG, 100).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(initializer);

    if (Epoll.isAvailable()) {
        bootstrap.channel(EpollServerSocketChannel.class);
    } else {
        bootstrap.channel(NioServerSocketChannel.class);
    }

    // Start the server
    final ChannelFuture future = bootstrap.bind(listenPort);
    environment.lifecycle().manage(new ChannelFutureManager(future));
    return future;
}

From source file:com.sohail.alam.http.server.SetupServer.java

License:Apache License

public void initialize() {
    final ServerBootstrap serverBootstrap = new ServerBootstrap();
    final EventLoopGroup boss = new NioEventLoopGroup();
    final EventLoopGroup worker = new NioEventLoopGroup();

    serverBootstrap.group(boss, worker).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, ServerProperties.PROP.SO_BACKLOG)
            .childOption(ChannelOption.TCP_NODELAY, ServerProperties.PROP.TCP_NODELAY)
            .childOption(ChannelOption.SO_KEEPALIVE, ServerProperties.PROP.SO_KEEPALIVE)
            .childOption(ChannelOption.SO_REUSEADDR, ServerProperties.PROP.SO_REUSEADDR)
            .childHandler(new HttpChannelInitializer());

    try {/*from ww w .ja  v  a  2s.c  om*/
        ChannelFuture future = serverBootstrap.bind(new InetSocketAddress(ip, port)).sync();
        if (future.isSuccess()) {
            LoggerManager.LOGGER.info("Http Server Started Successfully @ {}:{}", ip, port);
        } else {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
            LoggerManager.LOGGER.fatal("Http Server Start Failed. Can not bind to {}:{}", ip, port);
        }
    } catch (Exception e) {
        LoggerManager.LOGGER.fatal("Exception Caught while starting Http Server", e);
    }

}

From source file:com.splicemachine.olap.AsyncOlapNIOLayer.java

License:Apache License

public AsyncOlapNIOLayer(String host, int port) {
    InetSocketAddress socketAddr = new InetSocketAddress(host, port);
    Bootstrap bootstrap = new Bootstrap();
    NioEventLoopGroup group = new NioEventLoopGroup(5,
            new ThreadFactoryBuilder().setNameFormat("olapClientWorker-%d").setDaemon(true)
                    .setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                        @Override
                        public void uncaughtException(Thread t, Throwable e) {
                            LOG.error("[" + t.getName() + "] Unexpected error in AsyncOlapNIO pool: ", e);
                        }//w  w w  . j a va 2 s .c  o m
                    }).build());
    bootstrap.channel(NioSocketChannel.class).group(group).option(ChannelOption.SO_KEEPALIVE, true)
            .remoteAddress(socketAddr);

    //TODO -sf- this may be excessive network usage --consider a bounded pool to prevent over-connection?
    this.channelPool = new SimpleChannelPool(bootstrap, new AbstractChannelPoolHandler() {
        @Override
        public void channelCreated(Channel channel) throws Exception {
            ChannelPipeline p = channel.pipeline();
            p.addLast("frameEncoder", new LengthFieldPrepender(4));
            p.addLast("protobufEncoder", new ProtobufEncoder());
            p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1 << 30, 0, 4, 0, 4));
            p.addLast("protobufDecoder", decoder);
        }
    });
    executorService = group;
}

From source file:com.splicemachine.stream.ResultStreamer.java

License:Apache License

@Override
public Iterator<String> call(Integer partition, Iterator<T> locatedRowIterator) throws Exception {
    InetSocketAddress socketAddr = new InetSocketAddress(host, port);
    this.partition = partition;
    this.locatedRowIterator = locatedRowIterator;
    this.active = new CountDownLatch(1);
    taskContext = TaskContext.get();/* www .  j a va  2s. c o m*/
    Bootstrap bootstrap;
    ThreadFactory tf = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("ResultStreamer-" + host + ":" + port + "[" + partition + "]").build();
    this.workerGroup = new NioEventLoopGroup(2, tf);

    try {

        bootstrap = new Bootstrap();
        bootstrap.group(workerGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.handler(new OpenHandler(this));

        ChannelFuture futureConnect = bootstrap.connect(socketAddr).sync();

        active.await();
        long consumed = future.get();
        futureConnect.channel().closeFuture().sync();

        String result;
        if (consumed >= limit) {
            // We reached the limit, stop processing partitions
            result = "STOP";
        } else {
            // We didn't reach the limit, continue executing more partitions
            result = "CONTINUE";
        }
        return Arrays.asList(result).iterator();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:com.splicemachine.stream.StreamListenerServer.java

License:Apache License

public void start() throws StandardException {
    ThreadFactory tf = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("StreamerListenerServer-boss-%s").build();
    this.bossGroup = new NioEventLoopGroup(4, tf);
    tf = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("StreamerListenerServer-worker-%s").build();
    this.workerGroup = new NioEventLoopGroup(4, tf);
    try {//from   www  .  j  a  va2 s.  c o  m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new OpenHandler(this))
                .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(port).sync();

        this.serverChannel = f.channel();
        InetSocketAddress socketAddress = (InetSocketAddress) this.serverChannel.localAddress();
        String host = InetAddress.getLocalHost().getHostName();
        int port = socketAddress.getPort();

        this.hostAndPort = HostAndPort.fromParts(host, port);
        LOG.info("StreamListenerServer listening on " + hostAndPort);

    } catch (IOException e) {
        throw Exceptions.parseException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}