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:de.codecentric.boot.admin.server.web.client.InstanceWebClient.java

License:Apache License

private static WebClient createDefaultWebClient(Duration connectTimeout, Duration readTimeout,
        WebClientCustomizer customizer) {
    ReactorClientHttpConnector connector = new ReactorClientHttpConnector(
            options -> options.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeout.toMillis())
                    .compression(true).afterNettyContextInit(ctx -> {
                        ctx.addHandlerLast(
                                new ReadTimeoutHandler(readTimeout.toMillis(), TimeUnit.MILLISECONDS));
                    }));/* ww  w . j  a  v  a 2s. co  m*/

    WebClient.Builder builder = WebClient.builder().clientConnector(connector).defaultHeader(HttpHeaders.ACCEPT,
            ActuatorMediaType.V2_JSON, ActuatorMediaType.V1_JSON, MediaType.APPLICATION_JSON_VALUE);
    customizer.customize(builder);
    return builder.build();
}

From source file:de.jackwhite20.apex.tcp.pipeline.handler.SocketUpstreamHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) {

    final Channel inboundChannel = ctx.channel();

    Bootstrap b = new Bootstrap().group(inboundChannel.eventLoop()).channel(PipelineUtils.getChannel())
            .handler(new SocketDownstreamHandler(inboundChannel)).option(ChannelOption.TCP_NODELAY, true)
            // No initial connection should take longer than 4 seconds
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, BackendInfo.DEFAULT_TCP_TIMEOUT)
            .option(ChannelOption.AUTO_READ, false);

    ChannelFuture f = b.connect(backendInfo.getHost(), backendInfo.getPort());
    downstreamChannel = f.channel();/*from   w  w  w  .ja  v a  2s  . c  om*/
    f.addListener((ChannelFutureListener) future -> {

        if (future.isSuccess()) {
            inboundChannel.read();
        } else {
            inboundChannel.close();
        }
    });

    // Add the channel to the channel group
    Apex.getChannelGroup().add(inboundChannel);
}

From source file:de.jackwhite20.comix.handler.UpstreamHandler.java

License:Open Source License

public void connectDownstream(ByteBuf initPacket) {
    InetSocketAddress address = (InetSocketAddress) upstreamChannel.remoteAddress();
    TargetData target = this.strategy.selectTarget(address.getHostName(), address.getPort());

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(upstreamChannel.eventLoop()).channel(upstreamChannel.getClass())
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.AUTO_READ, false)
            .option(ChannelOption.SO_TIMEOUT, 5000).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000)
            .handler(downstreamHandler = new DownstreamHandler(client, upstreamChannel));

    ChannelFuture f = bootstrap.connect(target.getHost(), target.getPort());
    downstreamChannel = f.channel();/* ww  w.  j  a  v  a  2s  .c  om*/

    initialPackets.add(initPacket);

    f.addListener((future) -> {
        if (future.isSuccess()) {
            downstreamConnected = true;

            for (ByteBuf packet : initialPackets) {
                downstreamChannel.writeAndFlush(packet);
            }

            Comix.getLogger().log(Level.INFO, "Proxy",
                    "[" + client.getName() + "] <-> [Comix] <-> [" + target.getName() + "] tunneled");
        } else {
            upstreamChannel.close();
        }
    });
}

From source file:de.jackwhite20.japs.shared.nio.NioSocketClient.java

License:Open Source License

public boolean connect(String host, int port) {

    ChannelFuture channelFuture = new Bootstrap().group(PipelineUtils.newEventLoopGroup(1))
            .channel(PipelineUtils.getChannel()).handler(new ClientChannelInitializer(this))
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT).connect(host, port);

    channelFuture.awaitUninterruptibly();

    channel = channelFuture.channel();//from   w w w. jav  a2 s  . c  o m

    CountDownLatch countDownLatch = new CountDownLatch(1);

    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {

            connected = channelFuture.isSuccess();

            countDownLatch.countDown();
        }
    });

    try {
        countDownLatch.await(2, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return connected;
}

From source file:de.saxsys.synchronizefx.netty.base.client.NettyBasicClient.java

License:Open Source License

@Override
public void connect() throws SynchronizeFXException {
    this.eventLoopGroup = new NioEventLoopGroup();
    BasicChannelInitializerClient channelInitializer = createChannelInitializer();
    channelInitializer.setTopologyCallback(callback);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, TIMEOUT).handler(channelInitializer);

    LOG.info("Connecting to server");
    try {//ww  w  .  j  av a2  s. c  o m
        ChannelFuture future = bootstrap.connect(address);
        if (!future.await(TIMEOUT)) {
            disconnect();
            throw new SynchronizeFXException("Timeout while trying to connect to the server.");
        }
        if (!future.isSuccess()) {
            disconnect();
            throw new SynchronizeFXException("Connection to the server failed.", future.cause());
        }
        this.channel = future.channel();
        channel.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(final Future<? super Void> future) throws Exception {
                // stop the event loop
                eventLoopGroup.shutdownGracefully();
            }
        });
    } catch (InterruptedException e) {
        disconnect();
        throw new SynchronizeFXException(e);
    }
}

From source file:de.unipassau.isl.evs.ssh.core.network.Client.java

License:Open Source License

/**
 * Tries to establish a TCP connection to the Server with the given host and port.
 * If the connect ist successful, {@link #getHandshakeHandler()} is used to add the
 * required Handlers to the pipeline./*w w w .ja v a  2 s.c om*/
 * If the connection fails, {@link #channelClosed(Channel)} is called until to many retries are made and the Client
 * switches to searching the master via UDP discovery using the {@link UDPDiscoveryClient}.
 */
private void connectClient(InetSocketAddress address) {
    Log.i(TAG, "Client connecting to " + address);
    notifyClientConnecting(address.getHostString(), address.getPort());

    // TCP Connection
    Bootstrap b = new Bootstrap().group(requireComponent(ExecutionServiceComponent.KEY))
            .channel(NioSocketChannel.class).handler(getHandshakeHandler())
            .option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) TimeUnit.SECONDS.toMillis(5));

    // Wait for the start of the client
    channelFuture = b.connect(address);
    channelFuture.addListener(new ChannelFutureListener() {
        /**
         * Called once the operation completes, either because the connect was successful or because of an error.
         */
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                Log.v(TAG, "Channel open");
                channelOpen(future.channel());
            } else {
                Log.v(TAG, "Channel open failed");
                channelClosed(future.channel());
            }
        }
    });
    channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
        /**
         * Called once the connection is closed.
         */
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            Log.v(TAG, "Channel closed");
            channelClosed(future.channel());
        }
    });
}

From source file:deven.monitor.client.MonitorClient.java

License:Apache License

private void init() {
    System.out.println("--> initializing connection to " + host + ":" + port);

    group = new NioEventLoopGroup();
    try {// w w  w  . ja va2  s  .  co m
        CommandInit si = new CommandInit(null, false);
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(si);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);

        // Make the connection attempt.
        channel = b.connect(host, port).syncUninterruptibly();

        // want to monitor the connection to the server s.t. if we loose the
        // connection, we can try to re-establish it.
        ClientClosedListener ccl = new ClientClosedListener(this);
        channel.channel().closeFuture().addListener(ccl);

        System.out.println(channel.channel().localAddress() + " -> open: " + channel.channel().isOpen()
                + ", write: " + channel.channel().isWritable() + ", reg: " + channel.channel().isRegistered());

    } catch (Throwable ex) {
        System.out.println("failed to initialize the client connection " + ex.toString());
        ex.printStackTrace();
    }

}

From source file:divconq.bus.Bus.java

License:Open Source License

public void connect() {
    // never try to connect until init has run
    if (Hub.instance.isStopping())
        return;//from  w  ww  .  j  a  va 2s  .c  o m

    // if connect method is already running then skip - it will try again later 
    if (!this.connectLock.tryLock())
        return;

    try {
        // ==========================================================================
        //   Add client connections when not enough
        // ==========================================================================

        for (final SocketInfo info : this.connectors.values()) {
            HubRouter router = this.allocateOrGetHub(info.getHubId(), info.isGateway());

            if (router.isLocal())
                continue;

            // -------------------------------------------------
            // message port
            // -------------------------------------------------
            int conncount = router.getCountSessions(info);

            // add a coonection only once per call to connect (should be between 2 - 15 seconds between calls)
            if (conncount < info.getCount()) {
                Bootstrap b = new Bootstrap();

                b.group(this.getEventLoopGroup()).channel(NioSocketChannel.class)
                        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 250)
                        .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            public void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();

                                if (info.isUseSsl())
                                    pipeline.addLast("ssl",
                                            new SslHandler(SslContextFactory.getClientEngine()));

                                pipeline.addLast("http-codec", new HttpClientCodec());
                                pipeline.addLast("aggregator", new HttpObjectAggregator(8192)); // TODO is this too small?

                                pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                                pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config

                                pipeline.addLast("ws-handler", new ClientHandler(info));
                            }
                        });

                Logger.debug("dcBus Client connecting");

                try {
                    // must wait here to make sure we don't release connectLock too soon
                    // we want channel init (above) to complete before we try connect again
                    b.connect(info.getAddress()).sync();
                } catch (InterruptedException x) {
                    Logger.warn("dcBus Client interrupted while connecting: " + x);
                } catch (Exception x) {
                    Logger.debug("dcBus Client unable to connect: " + x);
                }
            }

            // -------------------------------------------------
            // stream port
            // -------------------------------------------------
            conncount = router.getCountStreamSessions(info);

            // add a coonection only once per call to connect (should be between 2 - 15 seconds between calls)
            if (conncount < info.getStreamCount()) {
                Bootstrap b = new Bootstrap();

                b.group(this.getEventLoopGroup()).channel(NioSocketChannel.class)
                        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 250)
                        .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            public void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();

                                if (info.isUseSsl())
                                    pipeline.addLast("ssl",
                                            new SslHandler(SslContextFactory.getClientEngine()));

                                // TODO consider compression

                                pipeline.addLast("decoder", new StreamDecoder());
                                pipeline.addLast("encoder", new StreamEncoder());

                                pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                                pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config

                                pipeline.addLast("handler", new StreamHandler(info, false));
                            }
                        });

                Logger.debug("dcBus Client stream connecting");

                try {
                    // must wait here to make sure we don't release connectLock too soon
                    // we want chanel init (above) to complete before we try connect again
                    b.connect(info.getStreamAddress()).addListener(new GenericFutureListener<ChannelFuture>() {
                        @Override
                        public void operationComplete(ChannelFuture cf) throws Exception {
                            if (!cf.isSuccess()) {
                                Logger.debug("dcBus Stream unable to connect: " + cf.cause());
                                return;
                            }

                            // client starts the HELLO thing once connected!
                            StreamMessage icmd = Hub.instance.getBus().getLocalHub()
                                    .buildStreamHello(info.getHubId());
                            cf.channel().writeAndFlush(icmd);
                        }
                    }).sync();
                } catch (InterruptedException x) {
                    Logger.warn("dcBus Client stream interrupted while connecting: " + x);
                } catch (Exception x) {
                    Logger.debug("dcBus Client stream unable to connect: " + x);
                }
            }
        }

        // ==========================================================================
        //   Add server binding when missing
        // ==========================================================================

        for (final SocketInfo info : this.listeners) {
            // only if not currently bound
            if (this.activelisteners.containsKey(info))
                continue;

            // -------------------------------------------------
            // message port
            // -------------------------------------------------
            ServerBootstrap b = new ServerBootstrap();

            b.group(this.getEventLoopGroup()).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                    //.option(ChannelOption.SO_BACKLOG, 125)         // this is probably not needed but serves as note to research
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            if (info.isUseSsl())
                                pipeline.addLast("ssl", new SslHandler(SslContextFactory.getServerEngine()));

                            pipeline.addLast("codec-http", new HttpServerCodec());
                            pipeline.addLast("aggregator", new HttpObjectAggregator(65536));

                            pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                            pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config

                            pipeline.addLast("handler", new ServerHandler(info));
                        }
                    });

            try {
                // must wait here, both to keep the activelisteners listeners up to date
                // but also to make sure we don't release connectLock too soon
                ChannelFuture bfuture = b.bind(info.getAddress()).sync();

                if (bfuture.isSuccess()) {
                    Logger.info("dcBus Message Server listening - now listening for dcMessages on TCP port "
                            + info.getPort());
                    this.activelisteners.put(info, bfuture.channel());
                } else
                    Logger.error("dcBus Server unable to bind: " + bfuture.cause());
            } catch (InterruptedException x) {
                Logger.warn("dcBus Server interrupted while binding: " + x);
            } catch (Exception x) {
                Logger.error("dcBus Server unable to bind: " + x);
            }

            // -------------------------------------------------
            // stream port
            // -------------------------------------------------
            b = new ServerBootstrap();

            b.group(this.getEventLoopGroup()).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                    //.option(ChannelOption.SO_BACKLOG, 125)         // this is probably not needed but serves as note to research
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            if (info.isUseSsl())
                                pipeline.addLast("ssl", new SslHandler(SslContextFactory.getServerEngine()));

                            // TODO consider compression

                            pipeline.addLast("decoder", new StreamDecoder());
                            pipeline.addLast("encoder", new StreamEncoder());

                            pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                            pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config

                            pipeline.addLast("handler", new StreamHandler(info, true));
                        }
                    });

            try {
                // must wait here, both to keep the activelisteners listeners up to date
                // but also to make sure we don't release connectLock too soon
                ChannelFuture bfuture = b.bind(info.getStreamAddress()).sync();

                if (bfuture.isSuccess()) {
                    Logger.info("dcBus Stream Server listening - now listening for dcStreams on TCP port "
                            + info.getPort());
                    this.activestreamlisteners.put(info, bfuture.channel());
                } else
                    Logger.error("dcBus Stream Server unable to bind: " + bfuture.cause());
            } catch (InterruptedException x) {
                Logger.warn("dcBus Stream Server interrupted while binding: " + x);
            } catch (Exception x) {
                Logger.error("dcBus Stream Server unable to bind: " + x);
            }
        }

        // ==========================================================================
        //   Remove server binding as needed
        // ==========================================================================

        for (final SocketInfo info : this.activelisteners.keySet()) {
            // all is well if in the listeners list
            if (this.listeners.contains(info))
                continue;

            // otherwise we don't want to bind anymore
            this.stopSocketListener(info);
        }
    } finally {
        this.connectLock.unlock();
    }
}

From source file:dorkbox.network.connection.EndPointClient.java

License:Apache License

/**
 * this is called by 2 threads. The startup thread, and the registration-in-progress thread
 *
 * NOTE: must be inside synchronize(bootstrapLock)!
 *//*from   w w  w .ja  v  a 2s .co m*/
private void doRegistration() {
    BootstrapWrapper bootstrapWrapper = bootstrapIterator.next();

    ChannelFuture future;

    if (connectionTimeout != 0) {
        // must be before connect
        bootstrapWrapper.bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeout);
    }

    try {
        // UDP : When this is CONNECT, a udp socket will ONLY accept UDP traffic from the remote address (ip/port combo).
        //       If the reply isn't from the correct port, then the other end will receive a "Port Unreachable" exception.

        future = bootstrapWrapper.bootstrap.connect();
        future.await(connectionTimeout);
    } catch (Exception e) {
        String errorMessage = "Could not connect to the " + bootstrapWrapper.type + " server at "
                + bootstrapWrapper.address + " on port: " + bootstrapWrapper.port;
        if (logger.isDebugEnabled()) {
            // extra info if debug is enabled
            logger.error(errorMessage, e);
        } else {
            logger.error(errorMessage);
        }

        return;
    }

    if (!future.isSuccess()) {
        Throwable cause = future.cause();

        // extra space here is so it aligns with "Connecting to server:"
        String errorMessage = "Connection refused  :" + bootstrapWrapper.address + " at "
                + bootstrapWrapper.type + " port: " + bootstrapWrapper.port;

        if (cause instanceof java.net.ConnectException) {
            if (cause.getMessage().contains("refused")) {
                logger.error(errorMessage);
            }

        } else {
            logger.error(errorMessage, cause);
        }

        return;
    }

    logger.trace("Waiting for registration from server.");

    manageForShutdown(future);
}

From source file:eu.jangos.realm.RealmServer.java

License:Apache License

/**
 * Main of the RealmServer program.//w w  w  . java  2 s.  co m
 *
 * @param args the command line arguments
 * @throws InterruptedException in case of interruption of the running
 * process.
 */
public static void main(String[] args) throws InterruptedException {

    logger.info("Starting JaNGOS realm server version " + VERSION + ".");
    logger.info("JaNGOS is an opensource project, check-out : https://github.com/Warkdev/JaNGOSRealm !");

    realm.setOffline(false);
    rs.save(realm);

    logger.info("Realm configuration: ");
    logger.info("Name: " + realm.getName());
    logger.info("Address: " + realm.getAddress() + ":" + realm.getPort());
    logger.info("Type: " + realm.getRealmtype().getType());
    logger.info("Timezone: " + realm.getRealmtimezone().getName());
    logger.info("Population: " + realm.getPopulation());
    logger.info("Players: " + realm.getCountPlayers() + "/" + realm.getMaxPlayers());

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();

        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new RealmPacketDecoder(), new RealmPacketEncoder(), new RealmAuthHandler(),
                                new ReadTimeoutHandler(TIMEOUT), new CharacterHandler());
                    }
                });

        ChannelFuture f;

        // Start the server.   
        try {
            HOST = InetAddress.getByAddress(realm.getAddress().getBytes());
            f = b.bind(HOST, PORT).sync();
            logger.info("JaNGOS realm server started listening on " + HOST.getHostAddress() + ":" + PORT);
        } catch (UnknownHostException ex) {
            f = b.bind(PORT);
            logger.info("JaNGOS realm server started listening on port " + PORT);
        }

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        logger.info("JaNGOS realm server shutting down.");

        // Indicating that this realm is offline.
        realm.setOffline(true);
        rs.save(realm);

        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}