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:ratpack.server.internal.DefaultRatpackServer.java

License:Apache License

protected Channel buildChannel(final ServerConfig serverConfig, final ChannelHandler handlerAdapter)
        throws InterruptedException {

    SslContext sslContext = serverConfig.getNettySslContext();
    this.useSsl = sslContext != null;

    ServerBootstrap serverBootstrap = new ServerBootstrap();

    serverConfig.getConnectTimeoutMillis().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, i);
        serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, i);
    });//w ww  .  ja  va  2s  . c  om
    serverConfig.getMaxMessagesPerRead().ifPresent(i -> {
        FixedRecvByteBufAllocator allocator = new FixedRecvByteBufAllocator(i);
        serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, allocator);
        serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, allocator);
    });
    serverConfig.getReceiveBufferSize().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.SO_RCVBUF, i);
        serverBootstrap.childOption(ChannelOption.SO_RCVBUF, i);
    });
    serverConfig.getWriteSpinCount().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.WRITE_SPIN_COUNT, i);
        serverBootstrap.childOption(ChannelOption.WRITE_SPIN_COUNT, i);
    });
    serverConfig.getConnectQueueSize().ifPresent(i -> serverBootstrap.option(ChannelOption.SO_BACKLOG, i));

    return serverBootstrap.group(execController.getEventLoopGroup())
            .channel(ChannelImplDetector.getServerSocketChannelImpl())
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();

                    new ConnectionIdleTimeout(pipeline, serverConfig.getIdleTimeout());

                    if (sslContext != null) {
                        SSLEngine sslEngine = sslContext.newEngine(PooledByteBufAllocator.DEFAULT);
                        pipeline.addLast("ssl", new SslHandler(sslEngine));
                    }

                    pipeline.addLast("decoder", new HttpRequestDecoder(serverConfig.getMaxInitialLineLength(),
                            serverConfig.getMaxHeaderSize(), serverConfig.getMaxChunkSize(), false));
                    pipeline.addLast("encoder", new HttpResponseEncoder());
                    pipeline.addLast("deflater", new IgnorableHttpContentCompressor());
                    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
                    pipeline.addLast("adapter", handlerAdapter);

                    ch.config().setAutoRead(false);
                }
            }).bind(buildSocketAddress(serverConfig)).sync().channel();
}

From source file:reactor.io.net.impl.netty.udp.NettyDatagramServer.java

License:Apache License

public NettyDatagramServer(@Nonnull Environment env, @Nonnull Dispatcher dispatcher,
        @Nullable InetSocketAddress listenAddress, @Nullable final NetworkInterface multicastInterface,
        @Nonnull final ServerSocketOptions options, @Nullable Codec<Buffer, IN, OUT> codec) {
    super(env, dispatcher, listenAddress, multicastInterface, options, codec);

    if (options instanceof NettyServerSocketOptions) {
        this.nettyOptions = (NettyServerSocketOptions) options;
    } else {//from w w w.j a va2  s.c  om
        this.nettyOptions = null;
    }

    if (null != nettyOptions && null != nettyOptions.eventLoopGroup()) {
        this.ioGroup = nettyOptions.eventLoopGroup();
    } else {
        int ioThreadCount = getDefaultEnvironment().getIntProperty("reactor.udp.ioThreadCount",
                Environment.PROCESSORS);
        this.ioGroup = new NioEventLoopGroup(ioThreadCount, new NamedDaemonThreadFactory("reactor-udp-io"));
    }

    final InternetProtocolFamily family = toNettyFamily(options.protocolFamily());

    this.bootstrap = new Bootstrap().group(ioGroup).option(ChannelOption.SO_RCVBUF, options.rcvbuf())
            .option(ChannelOption.SO_SNDBUF, options.sndbuf())
            .option(ChannelOption.SO_REUSEADDR, options.reuseAddr()).option(ChannelOption.AUTO_READ, false)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.timeout())
            .channelFactory(new ChannelFactory<Channel>() {
                @Override
                public Channel newChannel() {
                    return new NioDatagramChannel(family);
                }
            });

    if (null != listenAddress) {
        bootstrap.localAddress(listenAddress);
    } else {
        bootstrap.localAddress(NetUtil.LOCALHOST, 3000);
    }
    if (null != multicastInterface) {
        bootstrap.option(ChannelOption.IP_MULTICAST_IF, multicastInterface);
    }
}

From source file:reactor.ipc.netty.options.ClientOptions.java

License:Open Source License

static void defaultClientOptions(Bootstrap bootstrap) {
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000).option(ChannelOption.AUTO_READ, false)
            .option(ChannelOption.SO_RCVBUF, 1024 * 1024).option(ChannelOption.SO_SNDBUF, 1024 * 1024);
}

From source file:reactor.ipc.netty.options.ServerOptions.java

License:Open Source License

static void defaultServerOptions(ServerBootstrap bootstrap) {
    bootstrap.localAddress(LOCALHOST_AUTO_PORT).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_BACKLOG, 1000)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.SO_RCVBUF, 1024 * 1024).childOption(ChannelOption.SO_SNDBUF, 1024 * 1024)
            .childOption(ChannelOption.AUTO_READ, false).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.SO_LINGER, 0).childOption(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000);
}

From source file:sailfish.remoting.channel.AbstractConfigurableExchangeChannelGroup.java

License:Apache License

protected Bootstrap configureBoostrap(Address remoteAddress, int connectTimeout, NegotiateConfig config,
        ExchangeChannelGroup channelGroup, EventLoopGroup loopGroup, EventExecutorGroup executorGroup) {
    Bootstrap boot = newBootstrap();/*from ww  w  .ja va2  s .  c om*/
    if (null == loopGroup) {
        loopGroup = ClientEventGroup.INSTANCE.getLoopGroup();
    }
    if (null == executorGroup) {
        executorGroup = ClientEventGroup.INSTANCE.getExecutorGroup();
    }
    boot.group(loopGroup);
    boot.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
    boot.remoteAddress(remoteAddress.host(), remoteAddress.port());
    boot.handler(newChannelInitializer(config, channelGroup, executorGroup));
    return boot;
}

From source file:se.sics.gvod.net.NettyNetwork.java

License:Open Source License

/**
 * Start listening as a server at the given address..
 *
 * @param addr the address to listen at/*from  w w w. j  a v a2  s  .co  m*/
 * @param port the port number to listen at
 * @param bindAllNetworkIfs whether to bind on all network interfaces
 * @return true if listening was started
 * @throws ChannelException in case binding failed
 */
private boolean bindUdpPort(final InetAddress addr, final int port, final boolean bindAllNetworkIfs) {

    if (udpPortsToSockets.containsKey(port)) {
        return true;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioDatagramChannel.class)
            .handler(new NettyMsgHandler(component, Transport.UDP, msgDecoderClass));

    // Allow packets as large as up to 1600 bytes (default is 768).
    // You could increase or decrease this value to avoid truncated packets
    // or to improve memory footprint respectively.
    //
    // Please also note that a large UDP packet might be truncated or
    // dropped by your router no matter how you configured this option.
    // In UDP, a packet is truncated or dropped if it is larger than a
    // certain size, depending on router configuration. IPv4 routers
    // truncate and IPv6 routers drop a large packet. That's why it is
    // safe to send small packets in UDP.
    bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1500));
    bootstrap.option(ChannelOption.SO_RCVBUF, RECV_BUFFER_SIZE);

    bootstrap.option(ChannelOption.SO_SNDBUF, SEND_BUFFER_SIZE);
    // bootstrap.setOption("trafficClass", trafficClass);
    // bootstrap.setOption("soTimeout", soTimeout);
    // bootstrap.setOption("broadcast", broadcast);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MS);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);

    try {
        DatagramChannel c;
        if (bindAllNetworkIfs) {
            c = (DatagramChannel) bootstrap.bind(
                    //                        new InetSocketAddress(port)
                    port).sync().channel();
        } else {
            c = (DatagramChannel) bootstrap.bind(new InetSocketAddress(addr, port)).sync().channel();
        }

        addLocalSocket(new InetSocketAddress(addr, port), c);
        logger.debug("Successfully bound to ip:port {}:{}", addr, port);
    } catch (InterruptedException e) {
        logger.warn("Problem when trying to bind to {}:{}", addr.getHostAddress(), port);
        trigger(new Fault(e.getCause()), control);
        return false;
    }

    udpSocketsToBootstraps.put(new InetSocketAddress(addr, port), bootstrap);

    return true;
}

From source file:se.sics.gvod.net.NettyNetwork.java

License:Open Source License

/**
 * Connect to a TCP server.//from  w  ww  . j a  va 2 s . c o  m
 *
 * @param remoteAddress the remote address
 * @param localAddress the local address to bind to
 * @return true if connection succeeded
 * @throws ChannelException if connecting failed
 */
private boolean connectTcp(Address remoteAddress, Address localAddress) {
    InetSocketAddress remote = address2SocketAddress(remoteAddress);
    InetSocketAddress local = address2SocketAddress(localAddress);

    if (tcpSocketsToBootstraps.containsKey(remote)) {
        return true;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    NettyStreamHandler handler = new NettyStreamHandler(component, Transport.TCP);
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class)
            .handler(new NettyInitializer<SocketChannel>(handler, msgDecoderClass))
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MS)
            .option(ChannelOption.SO_REUSEADDR, true);

    try {
        SocketChannel c = (SocketChannel) bootstrap.connect(remote, local).sync().channel();
        addLocalSocket(remote, c);
        logger.debug("Successfully connected to ip:port {}", remote.toString());
    } catch (InterruptedException e) {
        logger.warn("Problem when trying to connect to {}", remote);
        trigger(new Fault(e.getCause()), control);
        return false;
    }

    tcpSocketsToBootstraps.put(remote, bootstrap);
    return true;
}

From source file:se.sics.gvod.net.NettyNetwork.java

License:Open Source License

/**
 * Connect to a UDT server.//from www. j  a v  a 2s .  c  o m
 *
 * @param remoteAddress the remote address
 * @param localAddress the local address to bind to
 * @return true if connection succeeded
 * @throws ChannelException if connecting failed
 */
private boolean connectUdt(Address remoteAddress, Address localAddress) {
    InetSocketAddress remote = address2SocketAddress(remoteAddress);
    InetSocketAddress local = address2SocketAddress(localAddress);

    if (udtSocketsToBootstraps.containsKey(remote)) {
        return true;
    }

    ThreadFactory workerFactory = new UtilThreadFactory("clientWorker");
    NioEventLoopGroup workerGroup = new NioEventLoopGroup(1, workerFactory, NioUdtProvider.BYTE_PROVIDER);
    NettyStreamHandler handler = new NettyStreamHandler(component, Transport.UDT);
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channelFactory(NioUdtProvider.BYTE_CONNECTOR)
            .handler(new NettyInitializer<UdtChannel>(handler, msgDecoderClass))
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MS)
            .option(ChannelOption.SO_REUSEADDR, true);

    try {
        UdtChannel c = (UdtChannel) bootstrap.connect(remote, local).sync().channel();
        addLocalSocket(remote, c);
        logger.debug("Successfully connected to ip:port {}", remote.toString());
    } catch (InterruptedException e) {
        logger.warn("Problem when trying to connect to {}", remote.toString());
        trigger(new Fault(e.getCause()), control);
        return false;
    }

    udtSocketsToBootstraps.put(remote, bootstrap);
    return true;
}

From source file:se.sics.kompics.network.netty.NettyNetwork.java

License:Open Source License

public NettyNetwork(NettyInit init) {
    System.setProperty("java.net.preferIPv4Stack", "true");

    self = init.self;/*from w  w w. ja v a  2 s .c  o  m*/
    boundPort = self.getPort();

    // Prepare Bootstraps
    bootstrapTCPClient = new Bootstrap();
    bootstrapTCPClient.group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
            .handler(new NettyInitializer<SocketChannel>(new StreamHandler(this, Transport.TCP)))
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MS)
            .option(ChannelOption.SO_REUSEADDR, true);
    bootstrapUDTClient = new Bootstrap();
    NioEventLoopGroup groupUDT = new NioEventLoopGroup(1, Executors.defaultThreadFactory(),
            NioUdtProvider.BYTE_PROVIDER);
    bootstrapUDTClient.group(groupUDT).channelFactory(NioUdtProvider.BYTE_CONNECTOR)
            .handler(new NettyInitializer<SocketChannel>(new StreamHandler(this, Transport.UDT)))
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MS)
            .option(ChannelOption.SO_REUSEADDR, true);

    subscribe(startHandler, control);
    subscribe(stopHandler, control);
    subscribe(msgHandler, net);
    subscribe(notifyHandler, net);
}

From source file:se.sics.kompics.network.netty.NettyNetwork.java

License:Open Source License

private boolean bindUdpPort(final InetAddress addr, final int port) {

    EventLoopGroup group = new NioEventLoopGroup();
    bootstrapUDP = new Bootstrap();
    bootstrapUDP.group(group).channel(NioDatagramChannel.class)
            .handler(new DatagramHandler(this, Transport.UDP));

    bootstrapUDP.option(ChannelOption.RCVBUF_ALLOCATOR,
            new AdaptiveRecvByteBufAllocator(1500, 1500, RECV_BUFFER_SIZE));
    bootstrapUDP.option(ChannelOption.SO_RCVBUF, RECV_BUFFER_SIZE);
    bootstrapUDP.option(ChannelOption.SO_SNDBUF, SEND_BUFFER_SIZE);
    // bootstrap.setOption("trafficClass", trafficClass);
    // bootstrap.setOption("soTimeout", soTimeout);
    // bootstrap.setOption("broadcast", broadcast);
    bootstrapUDP.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MS);
    bootstrapUDP.option(ChannelOption.SO_REUSEADDR, true);

    try {//  w w  w.  j av a2 s  . c  o  m
        InetSocketAddress iAddr = new InetSocketAddress(addr, port);
        DatagramChannel c = (DatagramChannel) bootstrapUDP.bind(iAddr).sync().channel();

        addLocalSocket(iAddr, c);
        LOG.info("Successfully bound to ip:port {}:{}", addr, port);
    } catch (InterruptedException e) {
        LOG.error("Problem when trying to bind to {}:{}", addr.getHostAddress(), port);
        return false;
    }

    return true;
}