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.titilink.camel.rest.client.CamelClient.java

License:LGPL

/**
 * <>//from w  w w  .j a v a2  s  .  co  m
 * ??
 */
private CamelClient(String host, int port, int connAmout, boolean ssl) {
    this.host = host;
    this.port = port;

    //Configure the client.
    workerGroup = new NioEventLoopGroup();
    bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(NioSocketChannel.class).handler(new HttpClientInitializer(ssl));
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.remoteAddress(this.host, this.port);

    //at least one connection
    this.connAmout = (connAmout > 0) ? connAmout : minConnectionNum;
    channelQueue = new LinkedBlockingQueue<Channel>();
}

From source file:com.titilink.camel.rest.server.CamelServer.java

License:LGPL

private static void run(int port, boolean supportSSL) {
    LOGGER.info("CamelServer run({}, {})", port, supportSSL);

    EventLoopGroup bossGroup = new NioEventLoopGroup(DEFAULT_BOSS_NIO_EVENT_NUM);
    BOSS_GROUP_LIST.add(bossGroup);// w  ww  .j a  v a 2 s  . c  om
    EventLoopGroup workerGroup = new NioEventLoopGroup(DEFAULT_NIO_EVENT_NUM);
    WORKER_GROUP_LIST.add(workerGroup);

    String host = AdapterRestletUtil.getProperty(SERVER_REST_IP, LOCAL_HOST);
    HttpConnector httpConnector = new RestletConnector(host, port, supportSSL);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new HttpServerInitializer(supportSSL, httpConnector));
        b.childOption(ChannelOption.SO_KEEPALIVE, true);
        b.childOption(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_BACKLOG, DEFAULT_SO_BACKLOG);

        Channel ch = b.bind(new InetSocketAddress(host, port)).sync().channel();
        CHANNEL_LIST.add(ch);
        ch.closeFuture().sync();
    } catch (InterruptedException e) {
        LOGGER.error("InterruptedException while start server.");
    } catch (Throwable t) {
        LOGGER.error("CamelServer run throws error.");
    } finally {
        LOGGER.info("CamelServer run() : shutdown");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.tongbanjie.tarzan.rpc.netty.NettyRpcClient.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyClientConfig.getClientWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override//from w w  w.  j  a  v a 2  s. com
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    this.bootstrap.group(this.eventLoopGroupWorker).channel(NioSocketChannel.class)//
            //
            .option(ChannelOption.TCP_NODELAY, true)
            //
            .option(ChannelOption.SO_KEEPALIVE, false)
            //
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyClientConfig.getConnectTimeoutMillis())
            //
            .option(ChannelOption.SO_SNDBUF, nettyClientConfig.getClientSocketSndBufSize())
            //
            .option(ChannelOption.SO_RCVBUF, nettyClientConfig.getClientSocketRcvBufSize())
            //
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(//
                            defaultEventExecutorGroup, //
                            new NettyEncoder(), //
                            new NettyDecoder(), //
                            new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()), //
                            new NettyConnectManageHandler(), //
                            new NettyClientHandler());
                }
            });

    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRpcClient.this.scanResponseTable();
            } catch (Exception e) {
                LOGGER.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);

    if (this.channelEventListener != null) {
        this.nettyEventExecutor.start();
    }
}

From source file:com.tongbanjie.tarzan.rpc.netty.NettyRpcServer.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyServerConfig.getServerWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override//from w w w  .j  ava 2  s . c  o m
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupSelector)
                    .channel(NioServerSocketChannel.class)
                    //
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //
                    .option(ChannelOption.SO_REUSEADDR, true)
                    //
                    .option(ChannelOption.SO_KEEPALIVE, false)
                    //
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    //
                    .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize())
                    //
                    .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize())
                    //
                    .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort()))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    //
                                    defaultEventExecutorGroup, //
                                    new NettyEncoder(), //
                                    new NettyDecoder(), //
                                    new IdleStateHandler(0, 0,
                                            nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), //
                                    new NettyConnectManageHandler(), //
                                    new NettyServerHandler());
                        }
                    });

    if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {
        childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    }

    try {
        ChannelFuture sync = this.serverBootstrap.bind().sync();
        InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress();
        this.port = addr.getPort();
    } catch (InterruptedException e1) {
        throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1);
    }

    if (this.channelEventListener != null) {
        this.nettyEventExecutor.start();
    }

    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRpcServer.this.scanResponseTable();
            } catch (Exception e) {
                LOGGER.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);

    LOGGER.info("Rpc server [port:{}] start success", port);
}

From source file:com.trinity.engine.protocol.detail.TrinityConnectionManager.java

License:Apache License

/**
 * Initialise the connection manager context
 *
 * @param configuration the configuration on which all connection executes
 *//*from  w w w .j av a 2 s . co  m*/
public void initialise(Protocol configuration) {
    mProtocol = configuration;
    mBootstrap.group(mBossGroup, mWorkerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ConnectionChannel(mProtocol.getLookupService(), this))
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true);
}

From source file:com.turn.ttorrent.client.io.PeerClient.java

License:Apache License

public void start() throws Exception {
    bootstrap = new Bootstrap();
    bootstrap.group(environment.getEventService());
    bootstrap.channel(environment.getEventLoopType().getClientChannelType());
    // SocketAddress address = environment.getLocalPeerListenAddress();
    // if (address != null) bootstrap.localAddress(address);
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    // bootstrap.option(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES));
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) TimeUnit.SECONDS.toMillis(10));
    // TODO: Derive from PieceHandler.DEFAULT_BLOCK_SIZE
    // bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1024 * 1024);
    // bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
}

From source file:com.turn.ttorrent.client.io.PeerServer.java

License:Apache License

/**
 * Create and start a new listening service for our torrents, reporting
 * with our peer ID on the given address.
 *
 * <p>// www .  ja v  a 2  s. co  m
 * This binds to the first available port in the client port range
 * PORT_RANGE_START to PORT_RANGE_END.
 * </p>
 */
public void start() throws Exception {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(environment.getEventService());
    bootstrap.channel(environment.getEventLoopType().getServerChannelType());
    bootstrap.option(ChannelOption.SO_BACKLOG, 128);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.childHandler(new ChannelInitializer() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new PeerServerHandshakeHandler(torrents));
        }
    });
    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    // bootstrap.childOption(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES));
    // TODO: Derive from PieceHandler.DEFAULT_BLOCK_SIZE
    // bootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1024 * 1024);
    // bootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
    SocketAddress address = environment.getLocalPeerListenAddress();
    if (address != null) {
        future = bootstrap.bind(address).sync();
    } else {
        BIND: {
            Exception x = new IOException("No available port for the BitTorrent client!");
            for (int i = PORT_RANGE_START; i <= PORT_RANGE_END; i++) {
                try {
                    future = bootstrap.bind(i).sync();
                    break BIND;
                } catch (InterruptedException e) {
                    throw e;
                } catch (Exception e) {
                    x = e;
                }
            }
            throw new IOException("Failed to find an address to bind in range [" + PORT_RANGE_START + ","
                    + PORT_RANGE_END + "]", x);
        }
    }
}

From source file:com.twocater.diamond.core.netty.NettyConnector.java

@Override
public void bind() throws Exception {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup);
    ChannelHandlerAdapter serverHandler = this.nettyHandlerFactory.createServerHandler();
    if (serverHandler != null) {
        serverBootstrap.handler(serverHandler);
    }//from w  w  w  . j  a v  a2s  . c  o m
    serverBootstrap.channel(NioServerSocketChannel.class);
    serverBootstrap.childHandler(this.nettyHandlerFactory.createChildHandler(connectorConfig.getTimeout()));

    serverBootstrap.option(ChannelOption.SO_BACKLOG, connectorConfig.getSo_backlog_parent());
    serverBootstrap.option(ChannelOption.SO_REUSEADDR, connectorConfig.isSo_reuseaddr_parent());

    //         serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);//??? netty
    //        serverBootstrap.childOption(ChannelOption.SO_TIMEOUT, 5000);//??? ?timeout??
    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, connectorConfig.isTcp_nodelay());
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, connectorConfig.isKeepAlive());

    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, connectorConfig.isSo_reuseaddr());
    serverBootstrap.childOption(ChannelOption.SO_LINGER, connectorConfig.getSo_linger());
    serverBootstrap.childOption(ChannelOption.SO_SNDBUF, connectorConfig.getSo_sndbuf());
    serverBootstrap.childOption(ChannelOption.SO_RCVBUF, connectorConfig.getSo_rcvbuf());

    channelFuture = serverBootstrap.bind(connectorConfig.getPort()).sync();
}

From source file:com.twocater.diamond.core.test.DiscardServer.java

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {// w w  w . j a v a2s.c  om
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new DiscardServerHandler());
            }
        });
        b.option(ChannelOption.SO_BACKLOG, 128);
        b.childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture f = b.bind(port).sync();
        System.out.println("bind");
        f.channel().closeFuture().sync();
        System.out.println("close");
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}

From source file:com.weibo.api.motan.transport.netty.NettyClient.java

License:Apache License

/**
 * ? netty clientBootstrap//from   w ww .  jav  a 2  s .  co m
 */
private void initClientBootstrap() {
    bootstrap = new Bootstrap();

    // ?connectTimeout500msnetty nio?BossThread?
    // ?timeout?
    int timeout = getUrl().getIntParameter(URLParamType.connectTimeout.getName(),
            URLParamType.connectTimeout.getIntValue());
    if (timeout <= 0) {
        throw new MotanFrameworkException("NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.",
                MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
    }

    // ??
    final int maxContentLength = url.getIntParameter(URLParamType.maxContentLength.getName(),
            URLParamType.maxContentLength.getIntValue());

    EventLoopGroup group = new NioEventLoopGroup();

    bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout)
            .handler(new ChannelInitializer<SocketChannel>() {

                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new NettyDecoder(codec, NettyClient.this, maxContentLength));
                    pipeline.addLast(new NettyEncoder(codec, NettyClient.this));
                    pipeline.addLast(new NettyChannelHandler(NettyClient.this, new MessageHandler() {

                        @Override
                        public Object handle(Channel channel, Object message) {
                            Response response = (Response) message;

                            NettyResponseFuture responseFuture = NettyClient.this
                                    .removeCallback(response.getRequestId());

                            if (responseFuture == null) {
                                LoggerUtil.warn(
                                        "NettyClient has response from server, but resonseFuture not exist,  requestId={}",
                                        response.getRequestId());
                                return null;
                            }

                            if (response.getException() != null) {
                                responseFuture.onFailure(response);
                            } else {
                                responseFuture.onSuccess(response);
                            }

                            return null;
                        }
                    }));
                }
            });
}