Example usage for io.netty.channel ChannelFuture sync

List of usage examples for io.netty.channel ChannelFuture sync

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture sync.

Prototype

@Override
    ChannelFuture sync() throws InterruptedException;

Source Link

Usage

From source file:org.rzo.netty.ahessian.bootstrap.DefaultClient.java

License:Apache License

private Channel connect() {

    ChannelFuture future = bootstrap.connect();
    // Wait until the connection attempt succeeds or fails.
    try {/*  www  .  j  av  a 2s  . c  o m*/
        Channel channel = future.sync().channel();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if (future.isSuccess()) {
        return future.channel();
    }
    return null;
}

From source file:org.rzo.netty.mcast.bridge.MulticastAdapter.java

License:Apache License

public static void main(String[] args) throws Exception {
    String host = args[0];//  w  w  w  .  ja  va  2s  .  c  o m
    int port = Integer.parseInt(args[1]);

    bootstrap = new Bootstrap();
    EventLoopGroup group = new OioEventLoopGroup();
    bootstrap.group(group);
    bootstrap.channel(OioDatagramChannel.class);

    bootstrap.remoteAddress(new InetSocketAddress(host, port));

    bootstrap.handler(new ChannelPipelineFactory() {
        public HandlerList getPipeline() {
            return ChannelPipelineFactory.handlerList(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (mcast != null && mcast.isInit())
                        mcast.send((ByteBuf) msg);
                }

                @Override
                public void channelActive(ChannelHandlerContext ctx) {
                    timer.schedule(new TimerTask() {
                        public void run() {
                            bootstrap.connect();
                        }
                    }, RECONNECT_DELAY);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
                    Throwable cause = e.getCause();
                    if (cause instanceof ConnectException) {
                        System.out.println("conection lost: reconnecting...");
                    }
                    ctx.channel().close();
                }

            });
        }
    });

    ChannelFuture f = bootstrap.connect();
    channel = f.sync().channel();

    mcast.init(new ChannelPipelineFactory() {
        public HandlerList getPipeline() {
            return ChannelPipelineFactory.handlerList(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    ByteBuf b = mcast.getMessage((ByteBuf) msg);
                    if (b == null)
                        return;
                    if (channel != null && channel.isActive())
                        channel.write(b);
                }

            });
        }
    });

}

From source file:org.waarp.ftp.core.config.FtpInternalConfiguration.java

License:Open Source License

/**
 * Try to add a Passive Channel listening to the specified local address
 * //from w  ww  . j  av a  2s.  c  om
 * @param address
 * @param ssl
 * @throws Reply425Exception
 *             in case the channel cannot be opened
 */
public void bindPassive(InetSocketAddress address, boolean ssl) throws Reply425Exception {
    configuration.bindLock();
    try {
        BindAddress bindAddress = hashBindPassiveDataConn.get(address);
        if (bindAddress == null) {
            logger.debug("Bind really to {}", address);
            Channel parentChannel = null;
            try {
                ChannelFuture future = null;
                if (ssl) {
                    future = passiveSslBootstrap.bind(address);
                } else {
                    future = passiveBootstrap.bind(address);
                }
                if (future.await(configuration.TIMEOUTCON)) {
                    parentChannel = future.sync().channel();
                } else {
                    logger.warn("Cannot open passive connection due to Timeout");
                    throw new Reply425Exception("Cannot open a Passive Connection due to Timeout");
                }
            } catch (ChannelException e) {
                logger.warn("Cannot open passive connection {}", e.getMessage());
                throw new Reply425Exception("Cannot open a Passive Connection");
            } catch (InterruptedException e) {
                logger.warn("Cannot open passive connection {}", e.getMessage());
                throw new Reply425Exception("Cannot open a Passive Connection");
            }
            bindAddress = new BindAddress(parentChannel);
            FtpChannelUtils.addDataChannel(parentChannel, configuration);
            hashBindPassiveDataConn.put(address, bindAddress);
        }
        bindAddress.nbBind++;
        logger.debug("Bind number to {} is {}", address, bindAddress.nbBind);
    } finally {
        configuration.bindUnlock();
    }
}

From source file:org.wso2.carbon.transport.http.netty.listener.ServerConnectorBootstrap.java

License:Open Source License

public boolean unBindInterface(HTTPServerConnector serverConnector) throws InterruptedException {
    if (!initialized) {
        log.error("ServerConnectorBootstrap is not initialized");
        return false;
    }//from   www . j  a v a2  s  . c o m

    //Remove cached channels and close them.
    ChannelFuture future = serverConnector.getChannelFuture();
    if (future != null) {
        ChannelFuture channelFuture = future.channel().close();
        channelFuture.sync();
        log.info("HttpConnectorListener stopped listening on host " + serverConnector.getHost() + " and port "
                + serverConnector.getPort());
        return true;
    }
    return false;
}

From source file:org.wso2.carbon.transport.http.netty.util.server.HttpServer.java

License:Open Source License

/**
 * Start the HttpServer//ww  w.  j  ava  2  s .c  o  m
 */
public void start() {
    bossGroup = new NioEventLoopGroup(this.bossGroupSize);
    workerGroup = new NioEventLoopGroup(this.workerGroupSize);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 100);
        b.childOption(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(channelInitializer);
        ChannelFuture ch = b.bind(new InetSocketAddress(TestUtil.TEST_HOST, port));
        ch.sync();
        logger.info("HttpServer started on port " + port);
    } catch (InterruptedException e) {
        logger.error("HTTP Server cannot start on port " + port);
    }
}

From source file:org.wso2.carbon.transport.http.netty.util.server.HttpsServer.java

License:Open Source License

/**
 * Start the HttpsServer/*from  www.  j a v  a 2s .  c om*/
 */
public void start() {
    bossGroup = new NioEventLoopGroup(this.bossGroupSize);
    workerGroup = new NioEventLoopGroup(this.workerGroupSize);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 100);
        b.childOption(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);

        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(ksName), ksPass);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, ctPass);

        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), null, null);
        ((HTTPServerInitializer) channelInitializer).setSslContext(sslContext);

        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(channelInitializer);
        ChannelFuture ch = b.bind(new InetSocketAddress(TestUtil.TEST_HOST, port));
        ch.sync();
        logger.info("HttpServer started on port " + port);
    } catch (Exception e) {
        logger.error("HTTP Server cannot start on port " + port);
    }
}

From source file:org.wso2.extension.siddhi.io.tcp.sink.TCPSink.java

License:Open Source License

@Override
public void publish(Object payload, DynamicOptions dynamicOptions) throws ConnectionUnavailableException {
    try {/*from   w  w  w  .j  a v  a  2  s.com*/
        byte[] message;
        if (payload instanceof String) {
            message = ((String) payload).getBytes(Charset.defaultCharset());
        } else if (payload instanceof ByteBuffer) {
            message = ((ByteBuffer) payload).array();
        } else {
            message = (byte[]) payload;
        }
        boolean isSync;
        if (sync != null) {
            isSync = sync;
        } else {
            isSync = Boolean.parseBoolean(syncOption.getValue(dynamicOptions));
        }
        if (isSync) {
            try {
                ChannelFuture future = tcpNettyClient.send(channelId, message);
                future.sync();
                if (!future.isSuccess()) {
                    throw new ConnectionUnavailableException(
                            "Error sending events to '" + hostAndPort + "' on channel '" + channelId + "', "
                                    + hostAndPort + ", " + future.cause().getMessage(),
                            future.cause());
                }
            } catch (InterruptedException e) {
                throw new ConnectionUnavailableException("Error sending events to '" + hostAndPort
                        + "' on channel '" + channelId + "', " + hostAndPort + ", " + e.getMessage(), e);
            }
        } else {
            ChannelFuture future = tcpNettyClient.send(channelId, message);
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        log.error("Error sending events to '" + hostAndPort + "' on channel '" + channelId
                                + "', " + future.cause() + ", dropping events ", future.cause());
                    }
                }
            });
            if (future.isDone() && !future.isSuccess()) {
                throw new ConnectionUnavailableException(
                        "Error sending events to '" + hostAndPort + "' on channel '" + channelId + "', "
                                + hostAndPort + ", " + future.cause().getMessage(),
                        future.cause());
            }
        }
    } catch (Throwable t) {
        throw new ConnectionUnavailableException("Error sending events to '" + hostAndPort + "' on channel '"
                + channelId + "', " + hostAndPort + ", " + t.getMessage(), t);
    }
}

From source file:p2p_server.P2p_server.java

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    List<ChannelFuture> futures = new ArrayList<>();
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();

    try {//from  ww w.  j  av  a2 s. com
        ServerBootstrap appboot = new ServerBootstrap();
        appboot.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 8192).childHandler(new AppChildChannelHandler(sslCtx));

        appboot.option(ChannelOption.SO_REUSEADDR, true);
        appboot.option(ChannelOption.TCP_NODELAY, true);
        appboot.childOption(ChannelOption.SO_KEEPALIVE, true);
        appboot.childOption(ChannelOption.SO_RCVBUF, 512);
        appboot.childOption(ChannelOption.SO_SNDBUF, 512);

        ServerBootstrap devboot = new ServerBootstrap();
        devboot.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 8192).childHandler(new DevChildChannelHandler(sslCtx));

        devboot.option(ChannelOption.SO_REUSEADDR, true);
        devboot.option(ChannelOption.TCP_NODELAY, true);
        devboot.childOption(ChannelOption.SO_KEEPALIVE, true);
        devboot.childOption(ChannelOption.SO_RCVBUF, 512);
        devboot.childOption(ChannelOption.SO_SNDBUF, 512);

        //ChannelFuture f = boostrap.bind(port).sync();
        futures.add(devboot.bind(5560));
        futures.add(appboot.bind(5561));
        for (ChannelFuture f : futures) {
            f.sync();
        }

        for (ChannelFuture f : futures) {
            f.channel().closeFuture().sync();
        }
        // ???
        //   f.channel().closeFuture().sync();

    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();

    }

}

From source file:pers.zlf.fhsp.SocksServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//  ww w.  ja va  2s . c om
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new SocksServerInitializer());

        ChannelFuture future = b.bind(Configuration.port()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info("Server started, listening on port {}", Configuration.port());
                    }
                }
            }
        });

        future.sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:sas.systems.imflux.session.rtp.AbstractRtpSession.java

License:Apache License

/**
 * {@inheritDoc}/*  w  ww .j a v a 2s. c  om*/
 */
@Override
public synchronized boolean init() {
    if (this.running.get()) {
        return true;
    }
    Class<? extends Channel> channelType;

    if (useNio) {
        // create data channel bootstrap
        //          EventLoopGroup bossGroup = new NioEventLoopGroup(5, Executors.defaultThreadFactory()); // if we want to use others than the defaults
        this.workerGroup = new NioEventLoopGroup();
        channelType = NioDatagramChannel.class;
    } else {
        this.workerGroup = new OioEventLoopGroup();
        channelType = OioDatagramChannel.class;
    }

    Bootstrap dataBootstrap = new Bootstrap();
    dataBootstrap.group(this.workerGroup).option(ChannelOption.SO_SNDBUF, this.sendBufferSize)
            .option(ChannelOption.SO_RCVBUF, this.receiveBufferSize)
            // option not set: "receiveBufferSizePredictorFactory", new FixedReceiveBufferSizePredictorFactory(this.receiveBufferSize)
            .channel(channelType) // use an UDP channel implementation => forces us to use AddressedEnvelope
            .handler(new ChannelInitializer<Channel>() { // is used to initialize the ChannelPipeline
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("decoder", UdpDataPacketDecoder.getInstance());
                    pipeline.addLast("encoder", UdpDataPacketEncoder.getInstance());
                    pipeline.addLast("handler", new UdpDataHandler(AbstractRtpSession.this));
                }
            });

    // create control channel bootstrap
    Bootstrap controlBootstrap = new Bootstrap();
    controlBootstrap.group(this.workerGroup).option(ChannelOption.SO_SNDBUF, this.sendBufferSize)
            .option(ChannelOption.SO_RCVBUF, this.receiveBufferSize)
            // option not set: "receiveBufferSizePredictorFactory", new FixedReceiveBufferSizePredictorFactory(this.receiveBufferSize)
            .channel(channelType) // use an UDP channel implementation => forces us to use AddressedEnvelope
            .handler(new ChannelInitializer<Channel>() { // is used to initialize the ChannelPipeline
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("decoder", UdpControlPacketDecoder.getInstance());
                    pipeline.addLast("encoder", UdpControlPacketEncoder.getInstance());
                    pipeline.addLast("handler", new UdpControlHandler(AbstractRtpSession.this));
                }
            });

    // create data channel
    SocketAddress dataAddress = this.localParticipant.getDataDestination();
    try {
        ChannelFuture future = dataBootstrap.bind(dataAddress);
        this.dataChannel = future.sync().channel(); // wait for future to complete and retrieve channel
    } catch (Exception e) {
        LOG.error("Failed to bind data channel for session with id " + this.id, e);
        shutdownEventLoopGroup();
        return false;
    }

    // create control channel
    SocketAddress controlAddress = this.localParticipant.getControlDestination();
    try {
        ChannelFuture future = controlBootstrap.bind(controlAddress);
        this.controlChannel = future.sync().channel(); // wait for future to complete and retrieve channel

    } catch (Exception e) {
        LOG.error("Failed to bind control channel for session with id " + this.id, e);
        this.dataChannel.close();
        shutdownEventLoopGroup();
        return false;
    }

    LOG.debug("Data & Control channels bound for RtpSession with id {}.", this.id);
    // Send first RTCP packet.
    this.joinSession(this.localParticipant.getSsrc());
    this.running.set(true);

    // Add the participant database cleaner.
    this.timer.newTimeout(new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (!running.get()) {
                return;
            }

            participantDatabase.cleanup();
            timer.newTimeout(this, participantDatabaseCleanup, TimeUnit.SECONDS);
        }
    }, this.participantDatabaseCleanup, TimeUnit.SECONDS);

    // Add the periodic RTCP report generator.
    if (this.automatedRtcpHandling) {
        this.timer.newTimeout(this, this.updatePeriodicRtcpSendInterval(), TimeUnit.SECONDS);
    }

    if (this.internalTimer) {
        this.timer.start();
    }

    return true;
}