Example usage for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS

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

Introduction

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

Prototype

ChannelOption CONNECT_TIMEOUT_MILLIS

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

Click Source Link

Usage

From source file:com.andrewkroh.cisco.xmlservices.DefaultXmlPushService.java

License:Apache License

@Override
protected void doStart() {
    ChannelInboundHandler handler = new XmlResponseChannelHandler(PHONE_KEY, PUSH_RESP_KEY);

    bootstrap = new Bootstrap();
    bootstrap.group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeoutMs)
            .handler(new HttpClientInitializer(handler)).validate();

    notifyStarted();/*from   w w  w. ja va  2s. c  o  m*/

    LOGGER.info("Service is now STARTED.");
}

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/*  ww  w  .  j  a  va 2 s  .co  m*/
    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.");
    }// ww  w .j  av a2 s.c om

    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.baidu.rigel.biplatform.tesseract.node.service.IndexAndSearchClient.java

License:Open Source License

public IndexAndSearchClient() {
    // channelMaps = new ConcurrentHashMap<NodeAddress, Channel>();
    actionHandlerMaps = new ConcurrentHashMap<String, ChannelHandler>();
    b = new Bootstrap();
    group = new NioEventLoopGroup();
    b.group(group);/*w  w w.  j  ava2 s. c  o  m*/
    b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("encode", new ObjectEncoder());
            pipeline.addLast("decode", new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
            //                pipeline.addLast("frameencoder",new LengthFieldPrepender(4,false));
            //                pipeline.addLast("framedecoder",new LengthFieldBasedFrameDecoder(1024*1024*1024, 0, 4,0,4));
        }
    });

    logger.info("IndexAndSearchClient init finished");
}

From source file:com.basho.riak.client.core.ConnectionPool.java

License:Apache License

/**
 * Starts this connection pool.//from  ww w.  j a  va  2s . c om
 * <p/>
 * If {@code minConnections} has been set, that number of active connections
 * will be started and placed into the available queue. Note that if they
 * can not be established due to the Riak node being down, a network issue,
 * etc this will not prevent the pool from changing to a started state.
 *
 * @return this
 */
public synchronized ConnectionPool start() {
    stateCheck(State.CREATED);
    if (bootstrap == null) {
        this.bootstrap = new Bootstrap().group(new NioEventLoopGroup()).channel(NioSocketChannel.class);
        ownsBootstrap = true;
    }

    bootstrap.handler(protocol.channelInitializer()).remoteAddress(new InetSocketAddress(remoteAddress, port));

    if (connectionTimeout > 0) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeout);
    }

    if (executor == null) {
        executor = Executors.newSingleThreadScheduledExecutor();
        ownsExecutor = true;
    }

    if (minConnections > 0) {
        List<Channel> minChannels = new LinkedList<Channel>();
        for (int i = 0; i < minConnections; i++) {
            Channel channel;
            try {
                channel = doGetConnection();
                minChannels.add(channel);
            } catch (ConnectionFailedException ex) {
                // no-op, we don't care right now
            }
        }

        for (Channel c : minChannels) {
            available.offerFirst(new ChannelWithIdleTime(c));
        }
    }

    idleReaperFuture = executor.scheduleWithFixedDelay(new IdleReaper(), 1, 5, TimeUnit.SECONDS);
    healthMonitorFuture = executor.scheduleWithFixedDelay(new HealthMonitorTask(), 1000, 500,
            TimeUnit.MILLISECONDS);
    state = State.RUNNING;
    logger.info("ConnectionPool started; {}:{} {}", remoteAddress, port, protocol);
    notifyStateListeners();
    return this;
}

From source file:com.basho.riak.client.core.ConnectionPool.java

License:Apache License

/**
 * Sets the connection timeout for this pool
 *
 * @param connectionTimeoutInMillis the connectionTimeout to set
 * @see Builder#withConnectionTimeout(int)
 *///from   ww  w. j av a 2  s  .c om
public void setConnectionTimeout(int connectionTimeoutInMillis) {
    stateCheck(State.CREATED, State.RUNNING, State.HEALTH_CHECKING);
    this.connectionTimeout = connectionTimeoutInMillis;
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeout);
}

From source file:com.basho.riak.client.core.RiakNode.java

License:Apache License

public synchronized RiakNode start() {
    stateCheck(State.CREATED);//from   w  w  w  .  j a  v  a2 s. c  om

    if (executor == null) {
        executor = Executors.newSingleThreadScheduledExecutor();
        ownsExecutor = true;
    }

    if (bootstrap == null) {
        bootstrap = new Bootstrap().group(new NioEventLoopGroup()).channel(NioSocketChannel.class);
        ownsBootstrap = true;
    }

    bootstrap.handler(new RiakChannelInitializer(this))
            .remoteAddress(new InetSocketAddress(remoteAddress, port));

    if (connectionTimeout > 0) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeout);
    }

    if (minConnections > 0) {
        List<Channel> minChannels = new LinkedList<Channel>();
        for (int i = 0; i < minConnections; i++) {
            Channel channel;
            try {
                channel = doGetConnection();
                minChannels.add(channel);
            } catch (ConnectionFailedException ex) {
                // no-op, we don't care right now
            }
        }

        for (Channel c : minChannels) {
            available.offerFirst(new ChannelWithIdleTime(c));
            c.closeFuture().addListener(inAvailableCloseListener);
        }
    }

    idleReaperFuture = executor.scheduleWithFixedDelay(new IdleReaper(), 1, 5, TimeUnit.SECONDS);
    healthMonitorFuture = executor.scheduleWithFixedDelay(new HealthMonitorTask(), 1000, 1000,
            TimeUnit.MILLISECONDS);

    state = State.RUNNING;
    logger.info("RiakNode started; {}:{}", remoteAddress, port);
    notifyStateListeners();
    return this;
}

From source file:com.basho.riak.client.core.RiakNode.java

License:Apache License

/**
 * Sets the connection timeout for new connections.
 *
 * @param connectionTimeoutInMillis the connectionTimeout to set
 * @return a reference to this RiakNode//from ww  w .ja  v a  2 s  . c o m
 * @see Builder#withConnectionTimeout(int)
 */
public RiakNode setConnectionTimeout(int connectionTimeoutInMillis) {
    stateCheck(State.CREATED, State.RUNNING, State.HEALTH_CHECKING);
    this.connectionTimeout = connectionTimeoutInMillis;
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeout);
    return this;
}

From source file:com.chenyang.proxy.http.HttpUserAgentForwardHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception {

    final Channel uaChannel = uaChannelCtx.channel();

    final HttpRemote apnProxyRemote = uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();

    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;

        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());

        if (remoteChannel != null && remoteChannel.isActive()) {
            HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote);
            remoteChannel.writeAndFlush(request);
        } else {//from   w  ww  .j av  a 2  s  . c om

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(uaChannel.eventLoop()).channel(NioSocketChannel.class)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .option(ChannelOption.AUTO_READ, false)
                    .handler(new HttpRemoteForwardChannelInitializer(uaChannel, this));

            ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getInetSocketAddress(),
                    new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0));
            remoteChannel = remoteConnectFuture.channel();
            remoteChannelMap.put(apnProxyRemote.getRemoteAddr(), remoteChannel);

            remoteConnectFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        future.channel().write(constructRequestForProxy((HttpRequest) msg, apnProxyRemote));

                        for (HttpContent hc : httpContentBuffer) {
                            future.channel().writeAndFlush(hc);

                            if (hc instanceof LastHttpContent) {
                                future.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future)
                                                    throws Exception {
                                                if (future.isSuccess()) {
                                                    future.channel().read();
                                                }

                                            }
                                        });
                            }
                        }
                        httpContentBuffer.clear();
                    } else {
                        HttpErrorUtil.writeAndFlush(uaChannel, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                        httpContentBuffer.clear();
                        future.channel().close();
                    }
                }
            });

        }
        ReferenceCountUtil.release(msg);
    } else {
        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());
        HttpContent hc = ((HttpContent) msg);
        if (remoteChannel != null && remoteChannel.isActive()) {
            remoteChannel.writeAndFlush(hc);

            if (hc instanceof LastHttpContent) {
                remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            future.channel().read();
                        }

                    }
                });
            }
        } else {
            httpContentBuffer.add(hc);
        }
    }

}

From source file:com.chenyang.proxy.http.HttpUserAgentTunnelHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception {

    if (msg instanceof HttpRequest) {
        // Channel uaChannel = uaChannelCtx.channel();

        // connect remote
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.AUTO_READ, false)
                .handler(new HttpTunnelChannelInitializer(uaChannelCtx.channel()));

        final HttpRemote apnProxyRemote = uaChannelCtx.channel().attr(HttpConnectionAttribute.ATTRIBUTE_KEY)
                .get().getRemote();/*from   w w w . ja v  a2  s.c  o m*/

        bootstrap
                .connect(apnProxyRemote.getInetSocketAddress(),
                        new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0))
                .addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(final ChannelFuture future1) throws Exception {
                        if (future1.isSuccess()) {
                            HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse(
                                    HttpVersion.HTTP_1_1,
                                    new HttpResponseStatus(200, "Connection established"));
                            uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse)
                                    .addListener(new ChannelFutureListener() {
                                        @Override
                                        public void operationComplete(ChannelFuture future2) throws Exception {
                                            // remove handlers
                                            uaChannelCtx.pipeline().remove("codec");
                                            uaChannelCtx.pipeline().remove(HttpPreHandler.HANDLER_NAME);
                                            uaChannelCtx.pipeline()
                                                    .remove(HttpUserAgentTunnelHandler.HANDLER_NAME);

                                            uaChannelCtx.pipeline()
                                                    .addLast(new HttpRelayHandler(
                                                            "UA --> " + apnProxyRemote.getRemoteAddr(),
                                                            future1.channel()));
                                        }

                                    });

                        } else {
                            if (uaChannelCtx.channel().isActive()) {
                                uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(ChannelFutureListener.CLOSE);
                            }
                        }
                    }
                });

    }
    ReferenceCountUtil.release(msg);
}