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:org.opendaylight.protocol.pcep.impl.PCEPProtocolSessionPromise.java

License:Open Source License

synchronized void connect() {
    final PCEPProtocolSessionPromise lock = this;

    try {/*from   w ww. j a  va 2  s. c  o m*/
        LOG.debug("Promise {} attempting connect for {}ms", lock, Integer.valueOf(this.connectTimeout));
        if (this.address.isUnresolved()) {
            this.address = new InetSocketAddress(this.address.getHostName(), this.address.getPort());
        }

        this.b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, this.connectTimeout);
        this.b.remoteAddress(this.address);
        final ChannelFuture connectFuture = this.b.connect();
        connectFuture.addListener(new PCEPProtocolSessionPromise.BootstrapConnectListener(lock));
        this.pending = connectFuture;
    } catch (Exception e) {
        LOG.info("Failed to connect to {}", this.address, e);
        this.setFailure(e);
    }
}

From source file:org.opendaylight.protocol.pcep.pcc.mock.protocol.PCCReconnectPromise.java

License:Open Source License

public synchronized void connect() {
    try {//from   w  ww. j av  a2 s.c om
        this.b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, this.connectTimeout);
        this.b.remoteAddress(this.address);
        final ChannelFuture cf = this.b.connect();
        cf.addListener(new BootstrapConnectListener(PCCReconnectPromise.this));
        this.pending = cf;
    } catch (final Exception e) {
        LOG.info("Failed to connect to {}", this.address, e);
        this.setFailure(e);
    }
}

From source file:org.opendaylight.sxp.core.service.ConnectFacade.java

License:Open Source License

/**
 * Create new Connection to Peer/*w  ww. j a  v a  2s.co  m*/
 *
 * @param node       SxpNode containing Security options
 * @param connection SxpConnection containing connection details
 * @param hf         HandlerFactory providing handling of communication
 * @return ChannelFuture callback
 */
public static ChannelFuture createClient(SxpNode node, SxpConnection connection, final HandlerFactory hf) {
    if (!Epoll.isAvailable()) {
        throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
    }
    Bootstrap bootstrap = new Bootstrap();
    if (connection.getPassword() != null && !connection.getPassword().isEmpty()) {
        bootstrap.option(EpollChannelOption.TCP_MD5SIG,
                Collections.singletonMap(connection.getDestination().getAddress(),
                        connection.getPassword().getBytes(StandardCharsets.US_ASCII)));
    }
    bootstrap.channel(EpollSocketChannel.class);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Configuration.NETTY_CONNECT_TIMEOUT_MILLIS);
    RecvByteBufAllocator recvByteBufAllocator = new FixedRecvByteBufAllocator(
            Configuration.getConstants().getMessageLengthMax());
    bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.localAddress(node.getSourceIp().getHostAddress(), 0);
    bootstrap.group(eventLoopGroup);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(hf.getDecoders());
            ch.pipeline().addLast(hf.getEncoders());
        }
    });
    return bootstrap.connect(connection.getDestination());
}

From source file:org.opendaylight.usc.client.netconf.ProtocolSessionPromise.java

License:Open Source License

synchronized void connect() {
    final Object lock = this;

    try {//from  w  w  w.  jav a2  s . c  om
        final int timeout = this.strategy.getConnectTimeout();

        LOG.debug("Promise {} attempting connect for {}ms", lock, timeout);

        this.b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout);

        LOG.warn("About to connect");

        // final ChannelFuture connectFuture = this.b.connect(this.address);

        final ChannelFuture connectFuture = plugin.connect(b, this.address);
        LOG.warn("Connect finished");
        // Add listener that attempts reconnect by invoking this method again.
        connectFuture.addListener(new BootstrapConnectListener(lock));
        this.pending = connectFuture;
    } catch (final Exception e) {
        LOG.info("Failed to connect to {}", address, e);
        setFailure(e);
    }
}

From source file:org.openremote.agent.protocol.AbstractNettyMessageProcessor.java

License:Open Source License

protected void configureChannel() {
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000);
}

From source file:org.redisson.client.RedisClient.java

License:Apache License

public RedisClient(final Timer timer, ExecutorService executor, EventLoopGroup group,
        Class<? extends SocketChannel> socketChannelClass, String host, int port, int connectTimeout,
        int commandTimeout) {
    if (timer == null) {
        throw new NullPointerException("timer param can't be null");
    }/*from w  w  w .j  a v a  2 s  . c  o  m*/
    this.executor = executor;
    this.timer = timer;
    addr = new InetSocketAddress(host, port);
    bootstrap = new Bootstrap().channel(socketChannelClass).group(group).remoteAddress(addr);
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addFirst(new ConnectionWatchdog(bootstrap, channels, timer), CommandEncoder.INSTANCE,
                    CommandBatchEncoder.INSTANCE, new CommandsQueue(),
                    new CommandDecoder(RedisClient.this.executor));
        }
    });

    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
    this.commandTimeout = commandTimeout;
}

From source file:org.rzo.yajsw.app.WrapperManagerImpl.java

License:Apache License

public void start() {
    try {//from   w ww  .j  a  v  a  2 s.c o  m
        // hack: avoid netty hangs on connect
        if (_config.getBoolean("wrapper.console.pipestreams", false)) {
            Socket dummy = new Socket("127.0.0.1", _port);
            OutputStream out = dummy.getOutputStream();
            out.close();
            dummy.close();
        }
    } catch (Throwable e1) {
        if (_debug > 1)
            e1.printStackTrace();
    }

    connector = new Bootstrap();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    // workerGroup.setIoRatio(99);
    connector.group(workerGroup);
    connector.channel(NioSocketChannel.class);

    connector.remoteAddress(new InetSocketAddress("127.0.0.1", _port));
    connector.option(ChannelOption.SO_REUSEADDR, true);
    connector.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10 * 1000);
    connector.option(ChannelOption.TCP_NODELAY, true);

    if (_debugComm)
        connector.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline()
                        .addLast(new io.netty.channel.ChannelHandler[] {
                                new SystemOutLoggingFilter("WrapperManager"),
                                new DelimiterBasedFrameDecoder(8192, true, Delimiters.nulDelimiter()),
                                new MessageEncoder(), new MessageDecoder(), new WrapperHandler() }

                );
            }

        });
    else
        connector.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline()
                        .addLast(new io.netty.channel.ChannelHandler[] {
                                new DelimiterBasedFrameDecoder(8192, true, Delimiters.nulDelimiter()),
                                new MessageEncoder(), new MessageDecoder(), new WrapperHandler() }

                );
            }

        });

    // pinger is a cycler with high priority threads
    // sends ping messages within a ping interval
    _pinger = new Cycler(getPingInterval(), 0,
            Executors.newCachedThreadPool(new DaemonThreadFactory("pinger", Thread.MAX_PRIORITY)),
            new Runnable() {
                long start = System.currentTimeMillis();

                public void run() {
                    ChannelFuture future;
                    if (_session != null && _session.isActive() && !_stopping && !_appearHanging) {
                        synchronized (_heapDataLock) {
                            if (_sendHeapData) {
                                if (minorGCDuration == -1)
                                    getGCData();
                                future = _session.writeAndFlush(
                                        new Message(Constants.WRAPPER_MSG_PING, "" + currentPercentHeap + ";"
                                                + minorGCDuration + ";" + fullGCDuration + ";" + lastUsedHeap));
                                currentPercentHeap = -1;
                                minorGCDuration = -1;
                                fullGCDuration = -1;
                            } else {
                                future = _session.writeAndFlush(new Message(Constants.WRAPPER_MSG_PING, ""));
                            }
                        }
                        try {
                            future.await(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        start = System.currentTimeMillis();
                    } else if ((_haltAppOnWrapper && (System.currentTimeMillis() - start) > _startupTimeout)
                            && !_stopping) {
                        System.out.println("no connection to wrapper during " + (_startupTimeout / 1000)
                                + " seconds -> System.exit(-1)");
                        System.out.println(
                                "if this is due to server overload consider increasing yajsw configuration property wrapper.startup.timeout");
                        System.exit(-1);
                    }
                }
            });
    _pinger.start();

    // connect
    // handler should process messages in a separate thread

    reconnect();
    /*
     * try { if (_config.getInt("wrapper.action.port") > 0) { _actionHandler
     * = new ActionHandler(this, _config); _actionHandler.start(); } } catch
     * (Exception ex) { log.info("could not start action handler " +
     * ex.getMessage()); }
     */

}

From source file:org.scache.network.client.TransportClientFactory.java

License:Apache License

/** Create a completely new {@link TransportClient} to the remote address. */
private TransportClient createClient(InetSocketAddress address) throws IOException {
    logger.debug("Creating new connection to " + address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(socketChannelClass)
            // Disable Nagle's Algorithm since we don't want packets to wait
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.connectionTimeoutMs())
            .option(ChannelOption.ALLOCATOR, pooledAllocator);

    final AtomicReference<TransportClient> clientRef = new AtomicReference<>();
    final AtomicReference<Channel> channelRef = new AtomicReference<>();

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override/*from www .j a v a  2 s . c  o m*/
        public void initChannel(SocketChannel ch) {
            TransportChannelHandler clientHandler = context.initializePipeline(ch);
            clientRef.set(clientHandler.getClient());
            channelRef.set(ch);
        }
    });

    // Connect to the remote server
    long preConnect = System.nanoTime();
    ChannelFuture cf = bootstrap.connect(address);
    if (!cf.awaitUninterruptibly(conf.connectionTimeoutMs())) {
        throw new IOException(
                String.format("Connecting to %s timed out (%s ms)", address, conf.connectionTimeoutMs()));
    } else if (cf.cause() != null) {
        throw new IOException(String.format("Failed to connect to %s", address), cf.cause());
    }

    TransportClient client = clientRef.get();
    Channel channel = channelRef.get();
    assert client != null : "Channel future completed successfully with null client";

    // Execute any client bootstraps synchronously before marking the Client as successful.
    long preBootstrap = System.nanoTime();
    logger.debug("Connection to {} successful, running bootstraps...", address);
    try {
        for (TransportClientBootstrap clientBootstrap : clientBootstraps) {
            clientBootstrap.doBootstrap(client, channel);
        }
    } catch (Exception e) { // catch non-RuntimeExceptions too as bootstrap may be written in Scala
        long bootstrapTimeMs = (System.nanoTime() - preBootstrap) / 1000000;
        logger.error("Exception while bootstrapping client after " + bootstrapTimeMs + " ms", e);
        client.close();
        throw Throwables.propagate(e);
    }
    long postBootstrap = System.nanoTime();

    logger.info("Successfully created connection to {} after {} ms ({} ms spent in bootstraps)", address,
            (postBootstrap - preConnect) / 1000000, (postBootstrap - preBootstrap) / 1000000);

    return client;
}

From source file:org.server.core.netty.tcp.BaseSession.java

License:Apache License

/**
 * /*w  ww .  ja  v a2 s .  c  o  m*/
 * 
 * @param millis
 *            
 */
public void setConnectTimeoutMillis(int millis) {
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, millis);
}

From source file:org.springframework.boot.autoconfigure.web.embedded.NettyWebServerFactoryCustomizer.java

License:Apache License

private NettyServerCustomizer getConnectionTimeOutCustomizer(int duration) {
    return (httpServer) -> httpServer.tcpConfiguration(
            (tcpServer) -> tcpServer.selectorOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, duration));
}