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.slyak.services.proxy.server.NettyProxyServer.java

License:Apache License

@SneakyThrows(InterruptedException.class)
public void start() {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);
    ServerBootstrap bootstrap = new ServerBootstrap();
    bossGroup = new NioEventLoopGroup(proxyProperties.getBoss());
    workerGroup = new NioEventLoopGroup(proxyProperties.getWorker());
    clientGroup = new NioEventLoopGroup(proxyProperties.getClient());
    try {/*from  ww  w .  j  av  a 2s .com*/
        bootstrap.group(bossGroup, workerGroup).channel(getChannelClass())
                .option(ChannelOption.SO_BACKLOG, proxyProperties.getBackLog())
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, proxyProperties.getConnectTimeout())

                .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_REUSEADDR, true)

                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //channel time out handler
                        pipeline.addLast(new IdleStateHandler(0, 0, 30));
                        pipeline.addLast(new IdleEventHandler());
                        //logging
                        pipeline.addLast(new LoggingHandler());

                        if (isRouter()) {
                            pipeline.addLast(getProxyHandler(proxyProperties));
                        } else {
                            pipeline.addLast(getCustomChannelHandlers(clientGroup));
                        }
                        pipeline.addLast(ExceptionHandler.INSTANCE);
                    }
                });
        //start server
        ChannelFuture future = bootstrap.bind(proxyProperties.getPort()).sync();
        log.debug("Starting proxy server , port is {}", proxyProperties.getPort());
        future.channel().closeFuture().sync();
    } finally {
        stop();
    }
}

From source file:com.system.distribute.server.FileClient.java

License:Apache License

public ChannelFuture run() throws Exception {
    // Configure the server.
    final Bootstrap bootstrap = BootstrapFactory.createBootstrap(ChannelType.NIO);

    bootstrap.handler(new FileClientHandler());
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);

    try {/*from   w ww. jav  a2  s .  co m*/
        final ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(host, port)).sync();
        channelFuture.awaitUninterruptibly();

    } catch (InterruptedException e) {

    }

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

    // Wait until the server socket is closed.
    f.channel().closeFuture().sync();
    return f;

}

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.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.turo.pushy.apns.ApnsChannelFactory.java

License:Open Source License

ApnsChannelFactory(final SslContext sslContext, final ApnsSigningKey signingKey,
        final ProxyHandlerFactory proxyHandlerFactory, final int connectTimeoutMillis,
        final long idlePingIntervalMillis, final long gracefulShutdownTimeoutMillis,
        final Http2FrameLogger frameLogger, final InetSocketAddress apnsServerAddress,
        final EventLoopGroup eventLoopGroup) {

    this.sslContext = sslContext;

    if (this.sslContext instanceof ReferenceCounted) {
        ((ReferenceCounted) this.sslContext).retain();
    }/*  w  w w  .ja  v  a 2s .c  om*/

    this.addressResolverGroup = proxyHandlerFactory == null
            ? new RoundRobinDnsAddressResolverGroup(
                    ClientChannelClassUtil.getDatagramChannelClass(eventLoopGroup),
                    DefaultDnsServerAddressStreamProvider.INSTANCE)
            : NoopAddressResolverGroup.INSTANCE;

    this.bootstrapTemplate = new Bootstrap();
    this.bootstrapTemplate.group(eventLoopGroup);
    this.bootstrapTemplate.option(ChannelOption.TCP_NODELAY, true);
    this.bootstrapTemplate.remoteAddress(apnsServerAddress);
    this.bootstrapTemplate.resolver(this.addressResolverGroup);

    if (connectTimeoutMillis > 0) {
        this.bootstrapTemplate.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis);
    }

    this.bootstrapTemplate.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) {
            final ChannelPipeline pipeline = channel.pipeline();

            if (proxyHandlerFactory != null) {
                pipeline.addFirst(proxyHandlerFactory.createProxyHandler());
            }

            final SslHandler sslHandler = sslContext.newHandler(channel.alloc());

            sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
                @Override
                public void operationComplete(final Future<Channel> handshakeFuture) {
                    if (handshakeFuture.isSuccess()) {
                        final String authority = channel.remoteAddress().getHostName();

                        final ApnsClientHandler.ApnsClientHandlerBuilder clientHandlerBuilder;

                        if (signingKey != null) {
                            clientHandlerBuilder = new TokenAuthenticationApnsClientHandler.TokenAuthenticationApnsClientHandlerBuilder()
                                    .signingKey(signingKey).authority(authority)
                                    .idlePingIntervalMillis(idlePingIntervalMillis);
                        } else {
                            clientHandlerBuilder = new ApnsClientHandler.ApnsClientHandlerBuilder()
                                    .authority(authority).idlePingIntervalMillis(idlePingIntervalMillis);
                        }

                        if (frameLogger != null) {
                            clientHandlerBuilder.frameLogger(frameLogger);
                        }

                        final ApnsClientHandler apnsClientHandler = clientHandlerBuilder.build();

                        if (gracefulShutdownTimeoutMillis > 0) {
                            apnsClientHandler.gracefulShutdownTimeoutMillis(gracefulShutdownTimeoutMillis);
                        }

                        // TODO Use a named constant when https://github.com/netty/netty/pull/8683 is available
                        pipeline.addLast(new FlushConsolidationHandler(256, true));
                        pipeline.addLast(
                                new IdleStateHandler(idlePingIntervalMillis, 0, 0, TimeUnit.MILLISECONDS));
                        pipeline.addLast(apnsClientHandler);
                        pipeline.remove(ConnectionNegotiationErrorHandler.INSTANCE);

                        channel.attr(CHANNEL_READY_PROMISE_ATTRIBUTE_KEY).get().trySuccess(channel);
                    } else {
                        tryFailureAndLogRejectedCause(channel.attr(CHANNEL_READY_PROMISE_ATTRIBUTE_KEY).get(),
                                handshakeFuture.cause());
                    }
                }
            });

            pipeline.addLast(sslHandler);
            pipeline.addLast(ConnectionNegotiationErrorHandler.INSTANCE);
        }
    });
}

From source file:com.vmware.admiral.compute.container.HealthChecker.java

License:Open Source License

private void healthCheckTcp(ContainerState containerState, HealthConfig healthConfig, String[] hostPortBindings,
        Consumer<ContainerStats> callback) {
    if (hostPortBindings == null) {
        determineContainerHostPort(containerState, healthConfig,
                (bindings) -> healthCheckTcp(containerState, healthConfig, bindings, callback));
        return;//from w w w . j a  va2s .c o m
    }

    Integer configPort = Integer.valueOf(hostPortBindings[1]);
    int port = configPort > 0 ? configPort : 80;
    Bootstrap bootstrap = new Bootstrap().group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
            .remoteAddress(new InetSocketAddress(hostPortBindings[0], port))
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, healthConfig.timeoutMillis)
            .handler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel arg0) throws Exception {
                    // Nothing to setup
                }
            });

    ChannelFuture channelFuture = bootstrap.connect();
    channelFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture result) throws Exception {
            handleHealthResponse(containerState, result.cause(), callback);
            result.channel().close();
        }

    });
}

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

License:Apache License

/**
 * ? netty clientBootstrap/*from  ww  w. j a v a2 s .  c  o 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;
                        }
                    }));
                }
            });
}

From source file:com.weibo.api.motan.transport.netty4.client.Netty4Client.java

License:Apache License

/**
 * ? netty clientBootstrap//from ww  w  .  java 2s  .c  o  m
 */
private void initClientBootstrap() {
    bootstrap = new Bootstrap();

    NioEventLoopGroup group = new NioEventLoopGroup();
    bootstrap.group(group).channel(NioSocketChannel.class)
            .handler(new Netty4ClientInitializer(url, codec, this));

    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);

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

From source file:com.wolfbe.configcenter.remoting.netty.NettyRemotingClient.java

License:Apache License

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

                private AtomicInteger threadIndex = new AtomicInteger(0);

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

    Bootstrap handler = 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 NettyConnetManageHandler(), //
                            new NettyClientHandler());
                }
            });

    this.timer.scheduleAtFixedRate(new TimerTask() {

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

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

From source file:com.xx_dev.apn.proxy.ApnProxyUserAgentForwardHandler.java

License:Apache License

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

    final Channel uaChannel = uaChannelCtx.channel();

    final ApnProxyRemote apnProxyRemote = uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get()
            .getRemote();/*w ww.j a v a2 s.  c o  m*/

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

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

        if (remoteChannel != null && remoteChannel.isActive()) {
            LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                    "Use old remote channel");
            HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote);
            remoteChannel.writeAndFlush(request);
        } else {
            LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                    "Create new remote channel");

            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 ApnProxyRemoteForwardChannelInitializer(uaChannel, this));

            // set local address
            if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) {
                bootstrap.localAddress(new InetSocketAddress(
                        (ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0));
            }

            ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getRemoteHost(),
                    apnProxyRemote.getRemotePort());

            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 {
                        LoggerUtil.error(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                                "Remote channel create fail");

                        // send error response
                        String errorMsg = "remote connect to "
                                + uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote()
                                        .getRemoteAddr()
                                + " fail";
                        HttpMessage errorResponseMsg = HttpErrorUtil
                                .buildHttpErrorMessage(HttpResponseStatus.INTERNAL_SERVER_ERROR, errorMsg);
                        uaChannel.writeAndFlush(errorResponseMsg);
                        httpContentBuffer.clear();

                        future.channel().close();
                    }
                }
            });

        }
        ReferenceCountUtil.release(msg);
    } else {
        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());

        HttpContent hc = ((HttpContent) msg);
        //hc.retain();

        //HttpContent _hc = hc.copy();

        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);
        }
    }

}