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:fr.letroll.ttorrentandroid.client.io.PeerClient.java

License:Apache License

public void start() throws Exception {
    group = new NioEventLoopGroup();
    bootstrap = new Bootstrap();
    bootstrap.group(group);//w w w  .  jav  a2 s  .com
    bootstrap.channel(NioSocketChannel.class);
    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));
    // bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, (int) TimeUnit.SECONDS.toMillis(10));
}

From source file:gash.router.client.CommConnection.java

License:Apache License

private void init() {
    System.out.println("--> initializing connection to " + host + ":" + port);
    // the queue to support client-side surging
    outbound = new LinkedBlockingDeque<CommandMessage>();
    group = new NioEventLoopGroup();
    try {//from  ww  w  .jav  a 2 s.  co  m
        CommInit si = new CommInit(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();

        System.out.println("Printing channel " + channel);

        // 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) {
        logger.error("failed to initialize the client connection", ex);
        ex.printStackTrace();
    }

    // start outbound message processor
    worker = new CommWorker(this);
    worker.setDaemon(true);
    worker.start();
}

From source file:gash.router.global.edges.GlobalEdgeMonitor.java

License:Apache License

private Channel connectToChannel(String host, int port) {
    Bootstrap b = new Bootstrap();
    NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
    GlobalInit globalInit = new GlobalInit(server, false);

    try {//  www.  j  av a  2s.  c  o  m
        b.group(nioEventLoopGroup).channel(NioSocketChannel.class).handler(globalInit);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        // Make the connection attempt.
    } catch (Exception e) {
        logger.error("Could not connect to the host " + host);
        return null;
    }
    return b.connect(host, port).syncUninterruptibly().channel();

}

From source file:gash.router.server.communication.CommConnection.java

License:Apache License

/**
 * abstraction of notification in the communication
 * /*from  ww w .jav a  2  s  .  co  m*/
 * @param listener
 */
/*public void addListener(CommListener listener) {
   CommHandler handler = connect().pipeline().get(CommHandler.class);
   if (handler != null)
 handler.addListener(listener);
}*/

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

    // the queue to support client-side surging
    //outbound = new LinkedBlockingDeque<CommandMessage>();

    group = new NioEventLoopGroup();
    try {
        CommInit si = new CommInit(false);
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(si);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100000);
        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) {
        logger.error("failed to initialize the client connection");//, ex);
        //ex.printStackTrace();
    }

    // start outbound message processor
    //worker = new CommWorker(this);
    //worker.setDaemon(true);
    //worker.start();
}

From source file:gash.router.server.edges.EdgeMonitor.java

License:Apache License

private Channel connectToChannel(String host, int port) {
    Bootstrap b = new Bootstrap();
    NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
    WorkInit workInit = new WorkInit(state, false);

    try {//from   www.  ja  va  2  s  .c o  m
        b.group(nioEventLoopGroup).channel(NioSocketChannel.class).handler(workInit);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        // Make the connection attempt.
    } catch (Exception e) {
        logger.error("Could not connect to the host " + host);
        return null;
    }
    return b.connect(host, port).syncUninterruptibly().channel();

}

From source file:herddb.network.netty.NettyConnector.java

License:Apache License

public static NettyChannel connect(String host, int port, boolean ssl, int connectTimeout, int socketTimeout,
        ChannelEventListener receiver, final ExecutorService callbackExecutor,
        final MultithreadEventLoopGroup networkGroup, final DefaultEventLoopGroup localEventsGroup)
        throws IOException {
    try {//from   www  . j a  v a2s  .  c  o  m
        final SslContext sslCtx = !ssl ? null
                : SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

        Class<? extends Channel> channelType;

        InetSocketAddress inet = new InetSocketAddress(host, port);
        SocketAddress address;
        String hostAddress = NetworkUtils.getAddress(inet);

        MultithreadEventLoopGroup group;
        if (LocalServerRegistry.isLocalServer(hostAddress, port, ssl)) {
            channelType = LocalChannel.class;
            address = new LocalAddress(hostAddress + ":" + port + ":" + ssl);
            group = localEventsGroup;
        } else {
            channelType = networkGroup instanceof EpollEventLoopGroup ? EpollSocketChannel.class
                    : NioSocketChannel.class;
            address = inet;
            group = networkGroup;
        }
        Bootstrap b = new Bootstrap();
        AtomicReference<NettyChannel> result = new AtomicReference<>();

        b.group(group).channel(channelType).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    public void initChannel(Channel ch) throws Exception {
                        try {
                            NettyChannel channel = new NettyChannel(host + ":" + port, ch, callbackExecutor);
                            result.set(channel);
                            channel.setMessagesReceiver(receiver);
                            if (ssl) {
                                ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), host, port));
                            }
                            if (socketTimeout > 0) {
                                ch.pipeline().addLast("readTimeoutHandler",
                                        new ReadTimeoutHandler(socketTimeout));
                            }
                            ch.pipeline().addLast("lengthprepender", new LengthFieldPrepender(4));
                            ch.pipeline().addLast("lengthbaseddecoder",
                                    new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                            //
                            ch.pipeline().addLast("messagedecoder", new ProtocolMessageDecoder());
                            ch.pipeline().addLast(new ClientInboundMessageHandler(channel));
                        } catch (Throwable t) {
                            LOGGER.log(Level.SEVERE, "error connecting", t);
                            ch.close();
                        }
                    }
                });

        LOGGER.log(Level.FINE, "connecting to {0}:{1} ssl={2} address={3}",
                new Object[] { host, port, ssl, address });
        b.connect(address).sync();
        NettyChannel nettyChannel = result.get();
        if (!nettyChannel.isValid()) {
            throw new IOException("returned channel is not valid");
        }
        return nettyChannel;
    } catch (InterruptedException ex) {
        throw new IOException(ex);
    }

}

From source file:io.advantageous.conekt.http.impl.HttpClientImpl.java

License:Open Source License

private void applyConnectionOptions(Bootstrap bootstrap) {
    bootstrap.option(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    if (options.getSendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }/* www .j  a v a  2  s. c  o  m*/
    if (options.getReceiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    if (options.getSoLinger() != -1) {
        bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());
    }
    if (options.getTrafficClass() != -1) {
        bootstrap.option(ChannelOption.IP_TOS, options.getTrafficClass());
    }
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeout());
    bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_REUSEADDR, options.isReuseAddress());
}

From source file:io.advantageous.conekt.net.impl.NetClientImpl.java

License:Open Source License

private void applyConnectionOptions(Bootstrap bootstrap) {
    bootstrap.option(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    if (options.getSendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }//  www . jav a 2 s . c  om
    if (options.getReceiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    if (options.getSoLinger() != -1) {
        bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());
    }
    if (options.getTrafficClass() != -1) {
        bootstrap.option(ChannelOption.IP_TOS, options.getTrafficClass());
    }
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeout());
    bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
}

From source file:io.aos.netty5.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void messageReceived(final ChannelHandlerContext ctx, final SocksRequest message) throws Exception {
    if (message instanceof Socks4CmdRequest) {
        final Socks4CmdRequest request = (Socks4CmdRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new GenericFutureListener<Future<Channel>>() {
            @Override//  w w w.ja v a 2  s .co  m
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ctx.channel().writeAndFlush(new Socks4CmdResponse(Socks4CmdStatus.SUCCESS))
                            .addListener(new ChannelFutureListener() {
                                @Override
                                public void operationComplete(ChannelFuture channelFuture) {
                                    ctx.pipeline().remove(SocksServerConnectHandler.this);
                                    outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                    ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                                }
                            });
                } else {
                    ctx.channel().writeAndFlush(new Socks4CmdResponse(Socks4CmdStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new Socks4CmdResponse(Socks4CmdStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CmdRequest) {
        final Socks5CmdRequest request = (Socks5CmdRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new GenericFutureListener<Future<Channel>>() {
            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ctx.channel()
                            .writeAndFlush(
                                    new Socks5CmdResponse(Socks5CmdStatus.SUCCESS, request.addressType()))
                            .addListener(new ChannelFutureListener() {
                                @Override
                                public void operationComplete(ChannelFuture channelFuture) {
                                    ctx.pipeline().remove(SocksServerConnectHandler.this);
                                    outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                    ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                                }
                            });
                } else {
                    ctx.channel().writeAndFlush(
                            new Socks5CmdResponse(Socks5CmdStatus.FAILURE, request.addressType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(
                            new Socks5CmdResponse(Socks5CmdStatus.FAILURE, request.addressType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else {
        ctx.close();
    }
}

From source file:io.atomix.catalyst.transport.netty.NettyClient.java

License:Apache License

@Override
public CompletableFuture<Connection> connect(Address address) {
    Assert.notNull(address, "address");
    ThreadContext context = ThreadContext.currentContextOrThrow();
    CompletableFuture<Connection> future = new ComposableFuture<>();

    LOGGER.info("Connecting to {}", address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(transport.eventLoopGroup()).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*  ww  w  .  j  a  v  a2  s . c  o  m*/
                protected void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (transport.properties().sslEnabled()) {
                        pipeline.addFirst(
                                new SslHandler(new NettyTls(transport.properties()).initSslEngine(true)));
                    }
                    pipeline.addLast(FIELD_PREPENDER);
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(transport.properties().maxFrameSize(), 0,
                            4, 0, 4));
                    pipeline.addLast(
                            new NettyHandler(connections, future::complete, context, transport.properties()));
                }
            });

    bootstrap.option(ChannelOption.TCP_NODELAY, transport.properties().tcpNoDelay());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, transport.properties().tcpKeepAlive());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, transport.properties().connectTimeout());
    bootstrap.option(ChannelOption.ALLOCATOR, ALLOCATOR);

    if (transport.properties().sendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, transport.properties().sendBufferSize());
    }
    if (transport.properties().receiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, transport.properties().receiveBufferSize());
    }

    bootstrap.connect(address.socketAddress()).addListener(channelFuture -> {
        if (channelFuture.isSuccess()) {
            LOGGER.info("Connected to {}", address);
        } else {
            context.execute(() -> future.completeExceptionally(channelFuture.cause()));
        }
    });
    return future;
}