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.antsdb.saltedfish.server.SaltedFish.java

License:Open Source License

/**
 * starting netty/* ww w . j av  a  2s .c o  m*/
 * 
 * @param port
 * @throws InterruptedException 
 */
void startNetty() throws Exception {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup(this.configService.getNettyWorkerThreadPoolSize());
    _log.info("netty worker pool size: {}", workerGroup.executorCount());

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new MysqlChannelInitializer(this)).option(ChannelOption.SO_BACKLOG, 128)
            .childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.

    _log.info("starting netty on port: " + this.configService.getPort());
    this.f = b.bind(this.configService.getPort()).sync();
}

From source file:com.athena.meerkat.agent.netty.MeerkatClient.java

License:Apache License

/**
 * <pre>/*from  w w w  .j  a v a2  s. c  o m*/
 * Netty Server   Bootstrap?  .
 * </pre>
 * 
 * @param bootstrap
 * @param group
 * @return
 */
public Bootstrap createBootstrap(Bootstrap bootstrap, EventLoopGroup group, String host) {
    if (bootstrap != null) {
        bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new LoggingHandler(LogLevel.WARN)).handler(initializer).remoteAddress(host, port)
                .connect().addListener(new MeerkatClientListener(this, host));
    }

    return bootstrap;
}

From source file:com.athena.peacock.agent.netty.PeacockClient.java

License:Apache License

/**
 * <pre>/*  w w w.j  a v a 2  s  .  co  m*/
 * Netty Server   Bootstrap?  .
 * </pre>
 * @param bootstrap
 * @param group
 * @return
 */
public Bootstrap createBootstrap(Bootstrap bootstrap, EventLoopGroup group, String host) {
    if (bootstrap != null) {
        bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new LoggingHandler(LogLevel.WARN)).handler(initializer).remoteAddress(host, port)
                .connect().addListener(new PeacockClientListener(this, host));
    }

    return bootstrap;
}

From source file:com.baidu.jprotobuf.pbrpc.management.HttpServer.java

License:Apache License

public void start(int port) {

    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//  w w w .  jav a2 s  .c  o m
                public void initChannel(SocketChannel ch) throws Exception {
                    // server??httpResponse?HttpResponseEncoder?
                    ch.pipeline().addLast(new HttpResponseEncoder());
                    // serverhttpRequest?HttpRequestDecoder?
                    ch.pipeline().addLast(new HttpRequestDecoder());
                    ch.pipeline().addLast(new HttpServerInboundHandler(rpcServer));
                }
            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

    serverBootstrap.bind(port).addListener(new ChannelFutureListener() {

        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = future.channel();
                // TODO notifyStarted();
            } else {
                // TODO notifyFailed(future.cause());
            }
        }
    });

    LOG.log(Level.INFO, "Http starting at port: " + port);
}

From source file:com.baidu.jprotobuf.pbrpc.transport.RpcClient.java

License:Apache License

public RpcClient(Class<? extends Channel> clientChannelClass, RpcClientOptions rpcClientOptions) {
    this.workerGroup = new NioEventLoopGroup();
    this.group(workerGroup);
    this.channel(clientChannelClass);
    this.handler(new RpcClientPipelineinitializer(this));
    this.rpcClientOptions = rpcClientOptions;
    this.option(ChannelOption.SO_REUSEADDR, rpcClientOptions.isReuseAddress());
    this.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, rpcClientOptions.getConnectTimeout());
    this.option(ChannelOption.SO_SNDBUF, rpcClientOptions.getSendBufferSize());
    this.option(ChannelOption.SO_RCVBUF, rpcClientOptions.getSendBufferSize());
    this.option(ChannelOption.SO_KEEPALIVE, rpcClientOptions.isKeepAlive());
    this.option(ChannelOption.TCP_NODELAY, rpcClientOptions.getTcpNoDelay());
    this.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR,
            new DefaultMessageSizeEstimator(rpcClientOptions.getReceiveBufferSize()));

    // add count//  w w  w  . j ava 2s . com
    INSTANCE_COUNT.incrementAndGet();
}

From source file:com.baidu.jprotobuf.pbrpc.transport.RpcServer.java

License:Apache License

public RpcServer(Class<? extends ServerChannel> serverChannelClass, RpcServerOptions serverOptions,
        RpcServiceRegistry rpcServiceRegistry) {
    if (rpcServiceRegistry == null) {
        throw new RuntimeException("protperty 'rpcServiceRegistry ' is null.");
    }/*from   w  w w  . j a v a 2  s.  co m*/

    if (serverOptions == null) {
        serverOptions = new RpcServerOptions();
    }

    this.bossGroup = new NioEventLoopGroup(serverOptions.getAcceptorThreads());
    this.workerGroup = new NioEventLoopGroup(serverOptions.getWorkThreads());
    this.group(this.bossGroup, this.workerGroup);
    this.channel(serverChannelClass);

    this.option(ChannelOption.SO_BACKLOG, serverOptions.getBacklog());

    this.childOption(ChannelOption.SO_KEEPALIVE, serverOptions.isKeepAlive());
    this.childOption(ChannelOption.SO_REUSEADDR, true);
    this.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    this.childOption(ChannelOption.TCP_NODELAY, serverOptions.isTcpNoDelay());
    this.childOption(ChannelOption.SO_LINGER, serverOptions.getSoLinger());
    this.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, serverOptions.getConnectTimeout());
    this.childOption(ChannelOption.SO_RCVBUF, serverOptions.getReceiveBufferSize());
    this.childOption(ChannelOption.SO_SNDBUF, serverOptions.getSendBufferSize());

    this.rpcServiceRegistry = rpcServiceRegistry;
    // do register meta service
    rpcServiceRegistry.doRegisterMetaService();
    this.rpcServerOptions = serverOptions;
    this.rpcServerPipelineInitializer = new RpcServerPipelineInitializer(rpcServiceRegistry, rpcServerOptions);
    this.childHandler(rpcServerPipelineInitializer);
}

From source file:com.beeswax.http.server.HttpServer.java

License:Apache License

public void run() throws InterruptedException {
    // Create event loop groups. One for incoming connections handling and
    // second for handling actual event by workers
    final NioEventLoopGroup bossGroup = new NioEventLoopGroup(serverConfig.bossGroupSize);
    final NioEventLoopGroup workerGroup = new NioEventLoopGroup();

    try {//  ww  w  .j  ava2s  .  c om
        ServerBootstrap bootStrap = new ServerBootstrap();
        bootStrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                // SO_BACKLOG : The maximum queue length for incoming connections.
                .option(ChannelOption.SO_BACKLOG, serverConfig.backlogSize)
                // TCP_NODELAY: option to disable Nagle's algorithm to achieve lower latency on every packet sent
                .option(ChannelOption.TCP_NODELAY, serverConfig.tcpNodelay)
                // SO_KEEPALIVE: option to enable keep-alive packets for a socket connection
                .childOption(ChannelOption.SO_KEEPALIVE, serverConfig.keepAlive)
                .childHandler(new HttpServerChannelInitializer(serverConfig, handlerFactory));

        // bind to port
        final ChannelFuture channelFuture = bootStrap.bind(serverConfig.port).sync();

        // Wait until the server socket is closed.
        channelFuture.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.buildria.mocking.stub.StubHttpServer.java

License:Open Source License

@Override
public StubHttpServer start() {
    Stopwatch sw = createStarted();//from   w  w  w  .  j a v  a2 s. c  om
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                // CHECKSTYLE:OFF
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    // CHECKSTYLE:ON
                    // int maxInitialLineLength, int maxHeaderSize, int maxChunkSize
                    ch.pipeline().addLast("decoder",
                            new HttpRequestDecoder(MAX_INITIALLINE_LENGH, MAX_HEADERS_SIZE, MAX_CHUNK_SIZE));
                    ch.pipeline().addLast("aggregator", new HttpObjectAggregator(MAX_CONTENT_LENGTH));
                    ch.pipeline().addLast("encoder", new HttpResponseEncoder());
                    ch.pipeline().addLast("deflater", new HttpContentCompressor());
                    if (config.isLogging()) {
                        ch.pipeline().addLast("logging", new LoggingHandler(StubHttpServer.class));
                    }
                    ch.pipeline().addLast("handler", new Handler());
                }
            }).option(ChannelOption.SO_BACKLOG, SO_BACKLOG).childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    int port = config.getPort();
    ChannelFuture f;
    try {
        f = b.bind(port).sync();
    } catch (InterruptedException ex) {
        throw new MockingException(ex);
    }
    f.awaitUninterruptibly();
    sw.stop();
    LOG.debug("### StubHttpServer(port:{}) started. It took {}", port, sw);
    return this;
}

From source file:com.caocao.nio.server.NettyServer.java

License:Apache License

public void initAndStart() {
    System.out.println("port:" + port);
    // Configure the server.
    bossGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);
    workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);
    try {//from www . j av  a2 s.  c  o  m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_SNDBUF, 5 * 1024)
                .option(ChannelOption.SO_SNDBUF, 5 * 1024)
                .option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(40, 64, 1024))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new CustomerInitializer());

        // Start the server.
        ChannelFuture f = b.bind(port).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        logger.error("netty??", e);
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.cdg.study.netty.time.TimeClient.java

License:Open Source License

public static void main(String[] args) throws Exception {
    //      String host = args[0];
    //      int port = Integer.parseInt(args[1]);
    String host = "localhost";
    int port = 8021;
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {/*from ww w. j a  va  2s .  com*/
        Bootstrap b = new Bootstrap(); // (1)
        b.group(workerGroup); // (2)
        b.channel(NioSocketChannel.class); // (3)
        b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
        b.handler(new ChannelInitializer<SocketChannel>() {

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

        // Start the client.
        ChannelFuture f = b.connect(host, port).sync(); // (5)

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
    }
}