Package io.netty.bootstrap

Examples of io.netty.bootstrap.Bootstrap


            SocketAddress redisAddress = socketAddressSupplier.get();

            logger.debug("Connecting to Redis, address: " + redisAddress);

            final Bootstrap redisBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup);
            redisBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) unit.toMillis(timeout));

            final ConnectionWatchdog watchdog = new ConnectionWatchdog(redisBootstrap, timer, socketAddressSupplier);

            redisBootstrap.handler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {

                    if (withReconnect) {
                        watchdog.setReconnect(true);
                        ch.pipeline().addLast(watchdog);
                    }

                    ch.pipeline().addLast(new ChannelGroupListener(channels),
                            new ConnectionEventTrigger(connectionEvents, connection), handler, connection);
                }
            });

            ChannelFuture future = redisBootstrap.connect(redisAddress);

            future.await();

            if (!future.isSuccess()) {
                if (future.cause() instanceof Exception) {
View Full Code Here


        final CommandHandler<K, V> commandHandler = new CommandHandler<K, V>(queue);
        final RedisSentinelAsyncConnectionImpl<K, V> connection = new RedisSentinelAsyncConnectionImpl<K, V>(commandHandler,
                codec, timeout, unit);

        logger.debug("Trying to get a Sentinel connection for one of: " + redisURI.getSentinels());
        final Bootstrap sentinelBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup);
        final ConnectionWatchdog watchdog = new ConnectionWatchdog(sentinelBootstrap, timer);
        watchdog.setReconnect(true);

        sentinelBootstrap.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {

                ch.pipeline().addLast(watchdog, new ChannelGroupListener(channels), watchdog, commandHandler,
                        new ConnectionEventTrigger(connectionEvents, connection));

            }
        });

        if (redisURI.getSentinels().isEmpty() && LettuceStrings.isNotEmpty(redisURI.getHost())) {
            sentinelBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                    (int) redisURI.getUnit().toMillis(redisURI.getTimeout()));
            ChannelFuture connect = sentinelBootstrap.connect(redisURI.getResolvedAddress());
            logger.debug("Connecting to Sentinel, address: " + redisURI.getResolvedAddress());
            try {
                connect.sync();
            } catch (InterruptedException e) {
                throw new RedisException(e.getMessage(), e);
            }
        } else {

            boolean connected = false;
            Exception causingException = null;
            for (RedisURI uri : redisURI.getSentinels()) {

                sentinelBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) uri.getUnit().toMillis(uri.getTimeout()));
                ChannelFuture connect = sentinelBootstrap.connect(uri.getResolvedAddress());
                logger.debug("Connecting to Sentinel, address: " + uri.getResolvedAddress());
                try {
                    connect.sync();
                    connected = true;
                } catch (Exception e) {
View Full Code Here

        DiskFileUpload.baseDirectory = null; // system temp directory
        DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
        DiskAttribute.baseDirectory = null; // system temp directory

        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class).handler(new HttpUploadClientIntializer(sslCtx));

            // Simple Get form: no factory used (not usable)
            List<Entry<String, String>> headers = formget(b, host, port, get, uriSimple);
            if (headers == null) {
                factory.cleanAllHttpData();
View Full Code Here

            final WebSocketClientHandler handler =
                    new WebSocketClientHandler(
                            WebSocketClientHandshakerFactory.newHandshaker(
                                    uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));

            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioSocketChannel.class)
             .handler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 protected void initChannel(SocketChannel ch) {
                     ChannelPipeline p = ch.pipeline();
                     if (sslCtx != null) {
                         p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                     }
                     p.addLast(
                             new HttpClientCodec(),
                             new HttpObjectAggregator(8192),
                             handler);
                 }
             });

            Channel ch = b.connect(uri.getHost(), port).sync().channel();
            handler.handshakeFuture().sync();

            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String msg = console.readLine();
View Full Code Here

    }

    public NioClient(final URI uri) {
        final BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("nio-client-%d").build();
        group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(), threadFactory);
        final Bootstrap b = new Bootstrap().group(group);

        try {
            final MessageSerializer serializer = new KryoMessageSerializerV1d0();
            b.channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(final SocketChannel ch) {
                            final ChannelPipeline p = ch.pipeline();
                            p.addLast(
                                    new NioGremlinResponseDecoder(serializer),
                                    new NioGremlinRequestEncoder(true, serializer),
                                    callbackResponseHandler);
                        }
                    });

            channel = b.connect(uri.getHost(), uri.getPort()).sync().channel();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
View Full Code Here

    }

    public WebSocketClient(final URI uri) {
        final BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("ws-client-%d").build();
        group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(), threadFactory);
        final Bootstrap b = new Bootstrap().group(group);

        final String protocol = uri.getScheme();
        if (!"ws".equals(protocol))
            throw new IllegalArgumentException("Unsupported protocol: " + protocol);

        try {
            final WebSocketClientHandler wsHandler =
                    new WebSocketClientHandler(
                            WebSocketClientHandshakerFactory.newHandshaker(
                                    uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));
            final MessageSerializer serializer = new KryoMessageSerializerV1d0();
            b.channel(NioSocketChannel.class)
             .handler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 protected void initChannel(final SocketChannel ch) {
                     final ChannelPipeline p = ch.pipeline();
                     p.addLast(
                             new HttpClientCodec(),
                             new HttpObjectAggregator(8192),
                             wsHandler,
                             new WebSocketGremlinRequestEncoder(true, serializer),
                             new WebSocketGremlinResponseDecoder(serializer),
                             callbackResponseHandler);
                 }
             });

            channel = b.connect(uri.getHost(), uri.getPort()).sync().channel();
            wsHandler.handshakeFuture().sync();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
View Full Code Here

    public NettyHttpConduit(Bus b, EndpointInfo ei, EndpointReferenceType t, NettyHttpConduitFactory conduitFactory)
        throws IOException {
        super(b, ei, t);
        factory = conduitFactory;
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class);
    }
View Full Code Here

                    .withName("NettyServerTCPWorker")
                    .build();
            wg = workerGroup;
        }
       
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(wg).channel(NioDatagramChannel.class);
        // We cannot set the child option here     
        bootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
        bootstrap.option(ChannelOption.SO_SNDBUF, configuration.getSendBufferSize());
        bootstrap.option(ChannelOption.SO_RCVBUF, configuration.getReceiveBufferSize());
        bootstrap.option(ChannelOption.SO_BROADCAST, configuration.isBroadcast());
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());
       
        // TODO need to find the right setting of below option
        // only set this if user has specified
        /*
        if (configuration.getReceiveBufferSizePredictor() > 0) {
            bootstrap.setOption("receiveBufferSizePredictorFactory",
                    new FixedReceiveBufferSizePredictorFactory(configuration.getReceiveBufferSizePredictor()));
        }*/
       
        if (configuration.getBacklog() > 0) {
            bootstrap.option(ChannelOption.SO_BACKLOG, configuration.getBacklog());
        }

        //TODO need to check the additional netty options
        /*
        if (configuration.getOptions() != null) {
            for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
                connectionlessBootstrap.setOption(entry.getKey(), entry.getValue());
            }
        }*/

        LOG.debug("Created ConnectionlessBootstrap {}", bootstrap);

        // set the pipeline factory, which creates the pipeline for each newly created channels
        bootstrap.handler(pipelineFactory);

        InetSocketAddress hostAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort());
        SubnetUtils multicastSubnet = new SubnetUtils(MULTICAST_SUBNET);

        if (multicastSubnet.getInfo().isInRange(configuration.getHost())) {
            ChannelFuture channelFuture = bootstrap.bind(hostAddress);
            channelFuture.awaitUninterruptibly();
            channel = channelFuture.channel();
            DatagramChannel datagramChannel = (DatagramChannel) channel;
            String networkInterface = configuration.getNetworkInterface() == null ? LOOPBACK_INTERFACE : configuration.getNetworkInterface();
            multicastNetworkInterface = NetworkInterface.getByName(networkInterface);
            ObjectHelper.notNull(multicastNetworkInterface, "No network interface found for '" + networkInterface + "'.");
            LOG.info("ConnectionlessBootstrap joining {}:{} using network interface: {}", new Object[]{configuration.getHost(), configuration.getPort(), multicastNetworkInterface.getName()});
            datagramChannel.joinGroup(hostAddress, multicastNetworkInterface).syncUninterruptibly();
            allChannels.add(datagramChannel);
        } else {
            LOG.info("ConnectionlessBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
            ChannelFuture channelFuture = bootstrap.bind(hostAddress);
            channelFuture.awaitUninterruptibly();
            channel = channelFuture.channel();
            allChannels.add(channel);
        }
    }
View Full Code Here

    protected ChannelFuture openConnection() throws Exception {
        ChannelFuture answer;

        if (isTcp()) {
            // its okay to create a new bootstrap for each new channel
            Bootstrap clientBootstrap = new Bootstrap();
            clientBootstrap.channel(NioSocketChannel.class);
            clientBootstrap.group(getWorkerGroup());
            clientBootstrap.option(ChannelOption.SO_KEEPALIVE, configuration.isKeepAlive());
            clientBootstrap.option(ChannelOption.TCP_NODELAY, configuration.isTcpNoDelay());
            clientBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
            clientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());

            //TODO need to check it later
            // set any additional netty options
            /*
            if (configuration.getOptions() != null) {
                for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
                    clientBootstrap.setOption(entry.getKey(), entry.getValue());
                }
            }*/

            // set the pipeline factory, which creates the pipeline for each newly created channels
            clientBootstrap.handler(pipelineFactory);
            answer = clientBootstrap.connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
            if (LOG.isDebugEnabled()) {
                LOG.debug("Created new TCP client bootstrap connecting to {}:{} with options: {}",
                        new Object[]{configuration.getHost(), configuration.getPort(), clientBootstrap});
            }
            return answer;
        } else {
            // its okay to create a new bootstrap for each new channel
            Bootstrap connectionlessClientBootstrap = new Bootstrap();
            connectionlessClientBootstrap.channel(NioDatagramChannel.class);
            connectionlessClientBootstrap.group(getWorkerGroup());
            connectionlessClientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());
            connectionlessClientBootstrap.option(ChannelOption.SO_BROADCAST, configuration.isBroadcast());
            connectionlessClientBootstrap.option(ChannelOption.SO_SNDBUF, configuration.getSendBufferSize());
            connectionlessClientBootstrap.option(ChannelOption.SO_RCVBUF, configuration.getReceiveBufferSize());

            //TODO need to check it later
            // set any additional netty options
            /*
            if (configuration.getOptions() != null) {
                for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
                    connectionlessClientBootstrap.setOption(entry.getKey(), entry.getValue());
                }
            }*/

            // set the pipeline factory, which creates the pipeline for each newly created channels
            connectionlessClientBootstrap.handler(pipelineFactory);
            // bind and store channel so we can close it when stopping
            ChannelFuture channelFuture = connectionlessClientBootstrap.bind(new InetSocketAddress(0));
            channelFuture.awaitUninterruptibly();
            Channel channel = channelFuture.channel();
            allChannels.add(channel);
            answer = connectionlessClientBootstrap.connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));

            if (LOG.isDebugEnabled()) {
                LOG.debug("Created new UDP client bootstrap connecting to {}:{} with options: {}",
                       new Object[]{configuration.getHost(), configuration.getPort(), connectionlessClientBootstrap});
            }
View Full Code Here

    super(rpcMapping);
    this.responseClass = responseClass;
    this.handshakeType = handshakeType;
    this.handshakeParser = handshakeParser;

    b = new Bootstrap() //
        .group(eventLoopGroup) //
        .channel(TransportCheck.getClientSocketChannel()) //
        .option(ChannelOption.ALLOCATOR, alloc) //
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30*1000)
        .option(ChannelOption.SO_REUSEADDR, true)
View Full Code Here

TOP

Related Classes of io.netty.bootstrap.Bootstrap

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.