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:org.apache.bookkeeper.proto.BookieNettyServer.java

License:Apache License

private void listenOn(InetSocketAddress address, BookieSocketAddress bookieAddress)
        throws InterruptedException {
    if (!conf.isDisableServerSocketBind()) {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.option(ChannelOption.ALLOCATOR, allocator);
        bootstrap.childOption(ChannelOption.ALLOCATOR, allocator);
        bootstrap.group(eventLoopGroup, eventLoopGroup);
        bootstrap.childOption(ChannelOption.TCP_NODELAY, conf.getServerTcpNoDelay());
        bootstrap.childOption(ChannelOption.SO_LINGER, conf.getServerSockLinger());
        bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
                new AdaptiveRecvByteBufAllocator(conf.getRecvByteBufAllocatorSizeMin(),
                        conf.getRecvByteBufAllocatorSizeInitial(), conf.getRecvByteBufAllocatorSizeMax()));
        bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(
                conf.getServerWriteBufferLowWaterMark(), conf.getServerWriteBufferHighWaterMark()));

        if (eventLoopGroup instanceof EpollEventLoopGroup) {
            bootstrap.channel(EpollServerSocketChannel.class);
        } else {//www .j  a v  a  2 s .com
            bootstrap.channel(NioServerSocketChannel.class);
        }

        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                synchronized (suspensionLock) {
                    while (suspended) {
                        suspensionLock.wait();
                    }
                }

                BookieSideConnectionPeerContextHandler contextHandler = new BookieSideConnectionPeerContextHandler();
                ChannelPipeline pipeline = ch.pipeline();

                // For ByteBufList, skip the usual LengthFieldPrepender and have the encoder itself to add it
                pipeline.addLast("bytebufList", ByteBufList.ENCODER_WITH_SIZE);

                pipeline.addLast("lengthbaseddecoder",
                        new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4));
                pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));

                pipeline.addLast("bookieProtoDecoder", new BookieProtoEncoding.RequestDecoder(registry));
                pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.ResponseEncoder(registry));
                pipeline.addLast("bookieAuthHandler", new AuthHandler.ServerSideHandler(
                        contextHandler.getConnectionPeer(), authProviderFactory));

                ChannelInboundHandler requestHandler = isRunning.get()
                        ? new BookieRequestHandler(conf, requestProcessor, allChannels)
                        : new RejectRequestHandler();
                pipeline.addLast("bookieRequestHandler", requestHandler);

                pipeline.addLast("contextHandler", contextHandler);
            }
        });

        // Bind and start to accept incoming connections
        Channel listen = bootstrap.bind(address.getAddress(), address.getPort()).sync().channel();
        if (listen.localAddress() instanceof InetSocketAddress) {
            if (conf.getBookiePort() == 0) {
                conf.setBookiePort(((InetSocketAddress) listen.localAddress()).getPort());
            }
        }
    }

    if (conf.isEnableLocalTransport()) {
        ServerBootstrap jvmBootstrap = new ServerBootstrap();
        jvmBootstrap.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
        jvmBootstrap.group(jvmEventLoopGroup, jvmEventLoopGroup);
        jvmBootstrap.childOption(ChannelOption.TCP_NODELAY, conf.getServerTcpNoDelay());
        jvmBootstrap.childOption(ChannelOption.SO_KEEPALIVE, conf.getServerSockKeepalive());
        jvmBootstrap.childOption(ChannelOption.SO_LINGER, conf.getServerSockLinger());
        jvmBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
                new AdaptiveRecvByteBufAllocator(conf.getRecvByteBufAllocatorSizeMin(),
                        conf.getRecvByteBufAllocatorSizeInitial(), conf.getRecvByteBufAllocatorSizeMax()));
        jvmBootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(
                conf.getServerWriteBufferLowWaterMark(), conf.getServerWriteBufferHighWaterMark()));

        if (jvmEventLoopGroup instanceof DefaultEventLoopGroup) {
            jvmBootstrap.channel(LocalServerChannel.class);
        } else if (jvmEventLoopGroup instanceof EpollEventLoopGroup) {
            jvmBootstrap.channel(EpollServerSocketChannel.class);
        } else {
            jvmBootstrap.channel(NioServerSocketChannel.class);
        }

        jvmBootstrap.childHandler(new ChannelInitializer<LocalChannel>() {
            @Override
            protected void initChannel(LocalChannel ch) throws Exception {
                synchronized (suspensionLock) {
                    while (suspended) {
                        suspensionLock.wait();
                    }
                }

                BookieSideConnectionPeerContextHandler contextHandler = new BookieSideConnectionPeerContextHandler();
                ChannelPipeline pipeline = ch.pipeline();

                pipeline.addLast("lengthbaseddecoder",
                        new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4));
                pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));

                pipeline.addLast("bookieProtoDecoder", new BookieProtoEncoding.RequestDecoder(registry));
                pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.ResponseEncoder(registry));
                pipeline.addLast("bookieAuthHandler", new AuthHandler.ServerSideHandler(
                        contextHandler.getConnectionPeer(), authProviderFactory));

                ChannelInboundHandler requestHandler = isRunning.get()
                        ? new BookieRequestHandler(conf, requestProcessor, allChannels)
                        : new RejectRequestHandler();
                pipeline.addLast("bookieRequestHandler", requestHandler);

                pipeline.addLast("contextHandler", contextHandler);
            }
        });

        // use the same address 'name', so clients can find local Bookie still discovering them using ZK
        jvmBootstrap.bind(bookieAddress.getLocalAddress()).sync();
        LocalBookiesRegistry.registerLocalBookieAddress(bookieAddress);
    }
}

From source file:org.apache.bookkeeper.proto.PerChannelBookieClient.java

License:Apache License

protected ChannelFuture connect() {
    final long startTime = MathUtils.nowInNano();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Connecting to bookie: {}", addr);
    }//from   ww  w . j a  va2 s .c o  m

    // Set up the ClientBootStrap so we can create a new Channel connection to the bookie.
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup);
    if (eventLoopGroup instanceof EpollEventLoopGroup) {
        bootstrap.channel(EpollSocketChannel.class);
    } else if (eventLoopGroup instanceof DefaultEventLoopGroup) {
        bootstrap.channel(LocalChannel.class);
    } else {
        bootstrap.channel(NioSocketChannel.class);
    }

    bootstrap.option(ChannelOption.ALLOCATOR, this.allocator);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.getClientConnectTimeoutMillis());
    bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(
            conf.getClientWriteBufferLowWaterMark(), conf.getClientWriteBufferHighWaterMark()));

    if (!(eventLoopGroup instanceof DefaultEventLoopGroup)) {
        bootstrap.option(ChannelOption.TCP_NODELAY, conf.getClientTcpNoDelay());
        bootstrap.option(ChannelOption.SO_KEEPALIVE, conf.getClientSockKeepalive());

        // if buffer sizes are 0, let OS auto-tune it
        if (conf.getClientSendBufferSize() > 0) {
            bootstrap.option(ChannelOption.SO_SNDBUF, conf.getClientSendBufferSize());
        }

        if (conf.getClientReceiveBufferSize() > 0) {
            bootstrap.option(ChannelOption.SO_RCVBUF, conf.getClientReceiveBufferSize());
        }
    }

    // In the netty pipeline, we need to split packets based on length, so we
    // use the {@link LengthFieldBasedFramDecoder}. Other than that all actions
    // are carried out in this class, e.g., making sense of received messages,
    // prepending the length to outgoing packets etc.
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            pipeline.addLast("bytebufList", ByteBufList.ENCODER_WITH_SIZE);
            pipeline.addLast("lengthbasedframedecoder",
                    new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4));
            pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));
            pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.RequestEncoder(extRegistry));
            pipeline.addLast("bookieProtoDecoder",
                    new BookieProtoEncoding.ResponseDecoder(extRegistry, useV2WireProtocol));
            pipeline.addLast("authHandler", new AuthHandler.ClientSideHandler(authProviderFactory,
                    txnIdGenerator, connectionPeer, useV2WireProtocol));
            pipeline.addLast("mainhandler", PerChannelBookieClient.this);
        }
    });

    SocketAddress bookieAddr = addr.getSocketAddress();
    if (eventLoopGroup instanceof DefaultEventLoopGroup) {
        bookieAddr = addr.getLocalAddress();
    }

    ChannelFuture future = bootstrap.connect(bookieAddr);
    future.addListener(contextPreservingListener(new ConnectionFutureListener(startTime)));
    future.addListener(x -> makeWritable());
    return future;
}

From source file:org.apache.camel.component.netty4.ClientModeTCPNettyServerBootstrapFactory.java

License:Apache License

protected void startServerBootstrap() throws Exception {
    // prefer using explicit configured thread pools

    EventLoopGroup wg = configuration.getWorkerGroup();

    if (wg == null) {
        // create new pool which we should shutdown when stopping as its not shared
        workerGroup = new NettyWorkerPoolBuilder().withWorkerCount(configuration.getWorkerCount())
                .withName("NettyServerTCPWorker").build();
        wg = workerGroup;/*from ww w.  j  ava 2  s.  co m*/
    }

    clientBootstrap = new Bootstrap();
    clientBootstrap.channel(NioSocketChannel.class);
    clientBootstrap.group(wg);
    clientBootstrap.option(ChannelOption.SO_KEEPALIVE, configuration.isKeepAlive());
    clientBootstrap.option(ChannelOption.TCP_NODELAY, configuration.isTcpNoDelay());
    clientBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
    clientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());

    LOG.debug("Created ClientBootstrap {}", clientBootstrap);
    clientBootstrap.handler(pipelineFactory);
    ChannelFuture channelFuture = clientBootstrap
            .connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
    if (LOG.isDebugEnabled()) {
        LOG.debug("Created new TCP client bootstrap connecting to {}:{} with options: {}",
                new Object[] { configuration.getHost(), configuration.getPort(), clientBootstrap });
    }
    LOG.info("ClientModeServerBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
    channel = openChannel(channelFuture);

}

From source file:org.apache.camel.component.netty4.NettyProducer.java

License:Apache License

protected ChannelFuture openConnection() throws Exception {
    ChannelFuture answer;/*from  w ww.ja  v  a 2s . co  m*/

    if (isTcp()) {
        // its okay to create a new bootstrap for each new channel
        Bootstrap clientBootstrap = new Bootstrap();
        clientBootstrap.channel(NioSocketChannel.class);
        clientBootstrap.group(getWorkerGroup());
        clientBootstrap.option(ChannelOption.SO_KEEPALIVE, configuration.isKeepAlive());
        clientBootstrap.option(ChannelOption.TCP_NODELAY, configuration.isTcpNoDelay());
        clientBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
        clientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());

        //TODO need to check it later
        // set any additional netty options
        /*
        if (configuration.getOptions() != null) {
        for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
            clientBootstrap.setOption(entry.getKey(), entry.getValue());
        }
        }*/

        // set the pipeline factory, which creates the pipeline for each newly created channels
        clientBootstrap.handler(pipelineFactory);
        answer = clientBootstrap
                .connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created new TCP client bootstrap connecting to {}:{} with options: {}",
                    new Object[] { configuration.getHost(), configuration.getPort(), clientBootstrap });
        }
        return answer;
    } else {
        // its okay to create a new bootstrap for each new channel
        Bootstrap connectionlessClientBootstrap = new Bootstrap();
        connectionlessClientBootstrap.channel(NioDatagramChannel.class);
        connectionlessClientBootstrap.group(getWorkerGroup());
        connectionlessClientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                configuration.getConnectTimeout());
        connectionlessClientBootstrap.option(ChannelOption.SO_BROADCAST, configuration.isBroadcast());
        connectionlessClientBootstrap.option(ChannelOption.SO_SNDBUF, configuration.getSendBufferSize());
        connectionlessClientBootstrap.option(ChannelOption.SO_RCVBUF, configuration.getReceiveBufferSize());

        //TODO need to check it later
        // set any additional netty options
        /*
        if (configuration.getOptions() != null) {
        for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
            connectionlessClientBootstrap.setOption(entry.getKey(), entry.getValue());
        }
        }*/

        // set the pipeline factory, which creates the pipeline for each newly created channels
        connectionlessClientBootstrap.handler(pipelineFactory);
        // bind and store channel so we can close it when stopping
        ChannelFuture channelFuture = connectionlessClientBootstrap.bind(new InetSocketAddress(0));
        channelFuture.awaitUninterruptibly();
        Channel channel = channelFuture.channel();
        allChannels.add(channel);
        answer = connectionlessClientBootstrap
                .connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));

        if (LOG.isDebugEnabled()) {
            LOG.debug("Created new UDP client bootstrap connecting to {}:{} with options: {}", new Object[] {
                    configuration.getHost(), configuration.getPort(), connectionlessClientBootstrap });
        }
        return answer;
    }
}

From source file:org.apache.camel.component.netty4.SingleTCPNettyServerBootstrapFactory.java

License:Apache License

protected void startServerBootstrap() {
    // prefer using explicit configured thread pools
    EventLoopGroup bg = configuration.getBossGroup();
    EventLoopGroup wg = configuration.getWorkerGroup();

    if (bg == null) {
        // create new pool which we should shutdown when stopping as its not shared
        bossGroup = new NettyServerBossPoolBuilder().withBossCount(configuration.getBossCount())
                .withName("NettyServerTCPBoss").build();
        bg = bossGroup;/*from   www .  j  a  v  a2  s. com*/
    }
    if (wg == null) {
        // create new pool which we should shutdown when stopping as its not shared
        workerGroup = new NettyWorkerPoolBuilder().withWorkerCount(configuration.getWorkerCount())
                .withName("NettyServerTCPWorker").build();
        wg = workerGroup;
    }

    //channelFactory = new NioServerSocketChannelFactory(bg, wg);

    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bg, wg).channel(NioServerSocketChannel.class);
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, configuration.isKeepAlive());
    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, configuration.isTcpNoDelay());
    serverBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
    serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());
    if (configuration.getBacklog() > 0) {
        serverBootstrap.option(ChannelOption.SO_BACKLOG, configuration.getBacklog());
    }

    // TODO set any additional netty options and child options
    /*if (configuration.getOptions() != null) {
    for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
        serverBootstrap.setOption(entry.getKey(), entry.getValue());
    }
    }*/

    // set the pipeline factory, which creates the pipeline for each newly created channels
    serverBootstrap.childHandler(pipelineFactory);

    LOG.debug("Created ServerBootstrap {}", serverBootstrap);

    LOG.info("ServerBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
    ChannelFuture channelFutrue = serverBootstrap
            .bind(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
    channelFutrue.awaitUninterruptibly();
    channel = channelFutrue.channel();
    // to keep track of all channels in use
    allChannels.add(channel);
}

From source file:org.apache.carbondata.core.dictionary.server.DictionaryServer.java

License:Apache License

/**
 * start dictionary server/*ww  w.java2s .  co  m*/
 *
 * @param port
 * @throws Exception
 */
public void startServer(int port) {
    long start = System.currentTimeMillis();
    dictionaryServerHandler = new DictionaryServerHandler();
    boss = new NioEventLoopGroup();
    worker = new NioEventLoopGroup();
    // Configure the server.
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, worker);
        bootstrap.channel(NioServerSocketChannel.class);

        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("DictionaryServerHandler", dictionaryServerHandler);
            }
        });
        bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.bind(port).sync();

        LOGGER.info("Dictionary Server started, Time spent " + (System.currentTimeMillis() - start)
                + " Listening on port " + port);
    } catch (Exception e) {
        LOGGER.error(e, "Dictionary Server Start Failed");
        throw new RuntimeException(e);
    }
}

From source file:org.apache.carbondata.core.dictionary.server.NonSecureDictionaryServer.java

License:Apache License

/**
 * Binds dictionary server to an available port.
 *
 *//*from w  ww. j  a  v a  2s  .co  m*/
@Override
public void bindToPort() {
    long start = System.currentTimeMillis();
    // Configure the server.
    int i = 0;
    while (i < 10) {
        int newPort = port + i;
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, worker);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("LengthDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 2, 0, 2));
                    pipeline.addLast("NonSecureDictionaryServerHandler", nonSecureDictionaryServerHandler);
                }
            });
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
            String hostToBind = findLocalIpAddress(LOGGER);
            //iteratively listening to newports
            InetSocketAddress address = hostToBind == null ? new InetSocketAddress(newPort)
                    : new InetSocketAddress(hostToBind, newPort);
            bootstrap.bind(address).sync();
            LOGGER.info("Dictionary Server started, Time spent " + (System.currentTimeMillis() - start)
                    + " Listening on port " + newPort);
            this.port = newPort;
            this.host = hostToBind;
            break;
        } catch (Exception e) {
            LOGGER.error("Dictionary Server Failed to bind to port:" + newPort, e);
            if (i == 9) {
                throw new RuntimeException("Dictionary Server Could not bind to any port");
            }
        }
        i++;
    }
}

From source file:org.apache.cassandra.transport.Server.java

License:Apache License

private void run() {
    // Configure the server.
    eventExecutorGroup = new RequestThreadPoolExecutor();

    boolean hasEpoll = enableEpoll ? Epoll.isAvailable() : false;
    if (hasEpoll) {
        workerGroup = new EpollEventLoopGroup();
        logger.info("Netty using native Epoll event loop");
    } else {//w  w  w .  j  ava  2  s .  c o  m
        workerGroup = new NioEventLoopGroup();
        logger.info("Netty using Java NIO event loop");
    }

    ServerBootstrap bootstrap = new ServerBootstrap().group(workerGroup)
            .channel(hasEpoll ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_LINGER, 0)
            .childOption(ChannelOption.SO_KEEPALIVE, DatabaseDescriptor.getRpcKeepAlive())
            .childOption(ChannelOption.ALLOCATOR, CBUtil.allocator)
            .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024)
            .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);

    final EncryptionOptions.ClientEncryptionOptions clientEnc = DatabaseDescriptor.getClientEncryptionOptions();
    if (clientEnc.enabled) {
        logger.info("Enabling encrypted CQL connections between client and server");
        bootstrap.childHandler(new SecureInitializer(this, clientEnc));
    } else {
        bootstrap.childHandler(new Initializer(this));
    }

    // Bind and start to accept incoming connections.
    logger.info("Using Netty Version: {}", Version.identify().entrySet());
    logger.info("Starting listening for CQL clients on {}...", socket);

    ChannelFuture bindFuture = bootstrap.bind(socket);
    if (!bindFuture.awaitUninterruptibly().isSuccess())
        throw new IllegalStateException(String.format("Failed to bind port %d on %s.", socket.getPort(),
                socket.getAddress().getHostAddress()));

    connectionTracker.allChannels.add(bindFuture.channel());
    isRunning.set(true);

    StorageService.instance.setRpcReady(true);
}

From source file:org.apache.dubbo.remoting.transport.netty4.NettyClient.java

License:Apache License

/**
 * Init bootstrap/*from ww  w  .  ja v a  2s  . c  o m*/
 *
 * @throws Throwable
 */
@Override
protected void doOpen() throws Throwable {
    final NettyClientHandler nettyClientHandler = new NettyClientHandler(getUrl(), this);
    bootstrap = new Bootstrap();
    bootstrap.group(nioEventLoopGroup).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            //.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout())
            .channel(NioSocketChannel.class);

    if (getConnectTimeout() < 3000) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);
    } else {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeout());
    }

    bootstrap.handler(new ChannelInitializer() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            int heartbeatInterval = UrlUtils.getHeartbeat(getUrl());
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                    .addLast("decoder", adapter.getDecoder()).addLast("encoder", adapter.getEncoder())
                    .addLast("client-idle-handler", new IdleStateHandler(heartbeatInterval, 0, 0, MILLISECONDS))
                    .addLast("handler", nettyClientHandler);
            String socksProxyHost = ConfigUtils.getProperty(SOCKS_PROXY_HOST);
            if (socksProxyHost != null) {
                int socksProxyPort = Integer
                        .parseInt(ConfigUtils.getProperty(SOCKS_PROXY_PORT, DEFAULT_SOCKS_PROXY_PORT));
                Socks5ProxyHandler socks5ProxyHandler = new Socks5ProxyHandler(
                        new InetSocketAddress(socksProxyHost, socksProxyPort));
                ch.pipeline().addFirst(socks5ProxyHandler);
            }
        }
    });
}

From source file:org.apache.dubbo.rpc.protocol.rest.NettyServer.java

License:Apache License

@Override
protected void doStart(URL url) {
    String bindIp = url.getParameter(BIND_IP_KEY, url.getHost());
    if (!url.isAnyHost() && NetUtils.isValidLocalHost(bindIp)) {
        server.setHostname(bindIp);// ww w .j  a  va 2  s  .co  m
    }
    server.setPort(url.getParameter(BIND_PORT_KEY, url.getPort()));
    Map<ChannelOption, Object> channelOption = new HashMap<ChannelOption, Object>();
    channelOption.put(ChannelOption.SO_KEEPALIVE, url.getParameter(KEEP_ALIVE_KEY, DEFAULT_KEEP_ALIVE));
    server.setChildChannelOptions(channelOption);
    server.setExecutorThreadCount(url.getParameter(THREADS_KEY, DEFAULT_THREADS));
    server.setIoWorkerCount(url.getParameter(IO_THREADS_KEY, DEFAULT_IO_THREADS));
    server.setMaxRequestSize(url.getParameter(PAYLOAD_KEY, DEFAULT_PAYLOAD));
    server.start();
}