Example usage for io.netty.channel ChannelFuture await

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

Introduction

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

Prototype

boolean await(long timeoutMillis) throws InterruptedException;

Source Link

Document

Waits for this future to be completed within the specified time limit.

Usage

From source file:com.qq.servlet.demo.thrift.netty.client.NettyThriftClientHandler.java

License:Apache License

@Override
protected void messageReceived(ChannelHandlerContext ctx, TBase msg) throws Exception {
    Channel ch = ctx.channel();/* w  ww .  j a  v a2 s  .  c  o  m*/
    AttributeKey<String> key = AttributeKey.valueOf("ASYNC_CONTEXT");
    Attribute<String> attr = ch.attr(key);
    System.out.println("----------->" + attr.get() + "\t" + msg);
    ChannelFuture future = ch.close();
    future.await(100);
}

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.ja va 2 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: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. j  ava  2s .c  o  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:org.apache.dubbo.remoting.transport.netty4.NettyChannel.java

License:Apache License

/**
 * Send message by netty and whether to wait the completion of the send.
 *
 * @param message message that need send.
 * @param sent whether to ack async-sent
 * @throws RemotingException throw RemotingException if wait until timeout or any exception thrown by method body that surrounded by try-catch.
 *///from  www  . ja  v a2 s  .  c  om
@Override
public void send(Object message, boolean sent) throws RemotingException {
    // whether the channel is closed
    super.send(message, sent);

    boolean success = true;
    int timeout = 0;
    try {
        ChannelFuture future = channel.writeAndFlush(message);
        if (sent) {
            // wait timeout ms
            timeout = getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT);
            success = future.await(timeout);
        }
        Throwable cause = future.cause();
        if (cause != null) {
            throw cause;
        }
    } catch (Throwable e) {
        throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress()
                + ", cause: " + e.getMessage(), e);
    }
    if (!success) {
        throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress()
                + "in timeout(" + timeout + "ms) limit");
    }
}

From source file:org.apache.spark.network.client.TransportClientFactory.java

License:Apache License

/** Create a completely new {@link TransportClient} to the remote address. */
private TransportClient createClient(InetSocketAddress address) throws IOException, InterruptedException {
    logger.debug("Creating new connection to {}", address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(socketChannelClass)
            // Disable Nagle's Algorithm since we don't want packets to wait
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.connectionTimeoutMs())
            .option(ChannelOption.ALLOCATOR, pooledAllocator);

    if (conf.receiveBuf() > 0) {
        bootstrap.option(ChannelOption.SO_RCVBUF, conf.receiveBuf());
    }/*from  www  .  ja va  2  s .  c  om*/

    if (conf.sendBuf() > 0) {
        bootstrap.option(ChannelOption.SO_SNDBUF, conf.sendBuf());
    }

    final AtomicReference<TransportClient> clientRef = new AtomicReference<>();
    final AtomicReference<Channel> channelRef = new AtomicReference<>();

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) {
            TransportChannelHandler clientHandler = context.initializePipeline(ch);
            clientRef.set(clientHandler.getClient());
            channelRef.set(ch);
        }
    });

    // Connect to the remote server
    long preConnect = System.nanoTime();
    ChannelFuture cf = bootstrap.connect(address);
    if (!cf.await(conf.connectionTimeoutMs())) {
        throw new IOException(
                String.format("Connecting to %s timed out (%s ms)", address, conf.connectionTimeoutMs()));
    } else if (cf.cause() != null) {
        throw new IOException(String.format("Failed to connect to %s", address), cf.cause());
    }

    TransportClient client = clientRef.get();
    Channel channel = channelRef.get();
    assert client != null : "Channel future completed successfully with null client";

    // Execute any client bootstraps synchronously before marking the Client as successful.
    long preBootstrap = System.nanoTime();
    logger.debug("Connection to {} successful, running bootstraps...", address);
    try {
        for (TransportClientBootstrap clientBootstrap : clientBootstraps) {
            clientBootstrap.doBootstrap(client, channel);
        }
    } catch (Exception e) { // catch non-RuntimeExceptions too as bootstrap may be written in Scala
        long bootstrapTimeMs = (System.nanoTime() - preBootstrap) / 1000000;
        logger.error("Exception while bootstrapping client after " + bootstrapTimeMs + " ms", e);
        client.close();
        throw Throwables.propagate(e);
    }
    long postBootstrap = System.nanoTime();

    logger.info("Successfully created connection to {} after {} ms ({} ms spent in bootstraps)", address,
            (postBootstrap - preConnect) / 1000000, (postBootstrap - preBootstrap) / 1000000);

    return client;
}

From source file:org.jboss.aerogear.simplepush.server.netty.NettySimplePushSockJSServerTest.java

License:Apache License

@AfterClass
public static void stopSimplePushServer() throws InterruptedException {
    final ChannelFuture disconnect = channel.disconnect();
    disconnect.await(1000);
    bossGroup.shutdownGracefully();//  w  ww . java  2s.c om
    workerGroup.shutdownGracefully();
    eventExecutorGroup.shutdownGracefully();
}

From source file:org.jfxvnc.ui.service.VncRenderService.java

License:Apache License

private boolean connect() throws Exception {
    connectProperty.set(true);//from   w w w. ja v  a 2  s. c o  m
    shutdown();
    workerGroup = new NioEventLoopGroup();

    String host = config.hostProperty().get();
    int port = config.portProperty().get() > 0 ? config.portProperty().get() : CONNECT_PORT;

    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);

    b.handler(new ProtocolInitializer(VncRenderService.this, config));

    logger.info("try to connect to {}:{}", host, port);
    ChannelFuture f = b.connect(host, port);
    f.await(5000);

    connectProperty.set(f.isSuccess());
    logger.info("connection {}", connectProperty.get() ? "established" : "failed");
    if (f.isCancelled()) {
        logger.warn("connection aborted");
    } else if (!f.isSuccess()) {
        logger.error("connection failed", f.cause());
        exceptionCaughtProperty.set(f.cause() != null ? f.cause()
                : new Exception("connection failed to host: " + host + ":" + port));
    }
    return connectProperty.get();
}

From source file:org.rzo.yajsw.app.WrapperManagerImpl.java

License:Apache License

public void start() {
    try {//ww  w  . j a v a2s.com
        // hack: avoid netty hangs on connect
        if (_config.getBoolean("wrapper.console.pipestreams", false)) {
            Socket dummy = new Socket("127.0.0.1", _port);
            OutputStream out = dummy.getOutputStream();
            out.close();
            dummy.close();
        }
    } catch (Throwable e1) {
        if (_debug > 1)
            e1.printStackTrace();
    }

    connector = new Bootstrap();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    // workerGroup.setIoRatio(99);
    connector.group(workerGroup);
    connector.channel(NioSocketChannel.class);

    connector.remoteAddress(new InetSocketAddress("127.0.0.1", _port));
    connector.option(ChannelOption.SO_REUSEADDR, true);
    connector.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10 * 1000);
    connector.option(ChannelOption.TCP_NODELAY, true);

    if (_debugComm)
        connector.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline()
                        .addLast(new io.netty.channel.ChannelHandler[] {
                                new SystemOutLoggingFilter("WrapperManager"),
                                new DelimiterBasedFrameDecoder(8192, true, Delimiters.nulDelimiter()),
                                new MessageEncoder(), new MessageDecoder(), new WrapperHandler() }

                );
            }

        });
    else
        connector.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline()
                        .addLast(new io.netty.channel.ChannelHandler[] {
                                new DelimiterBasedFrameDecoder(8192, true, Delimiters.nulDelimiter()),
                                new MessageEncoder(), new MessageDecoder(), new WrapperHandler() }

                );
            }

        });

    // pinger is a cycler with high priority threads
    // sends ping messages within a ping interval
    _pinger = new Cycler(getPingInterval(), 0,
            Executors.newCachedThreadPool(new DaemonThreadFactory("pinger", Thread.MAX_PRIORITY)),
            new Runnable() {
                long start = System.currentTimeMillis();

                public void run() {
                    ChannelFuture future;
                    if (_session != null && _session.isActive() && !_stopping && !_appearHanging) {
                        synchronized (_heapDataLock) {
                            if (_sendHeapData) {
                                if (minorGCDuration == -1)
                                    getGCData();
                                future = _session.writeAndFlush(
                                        new Message(Constants.WRAPPER_MSG_PING, "" + currentPercentHeap + ";"
                                                + minorGCDuration + ";" + fullGCDuration + ";" + lastUsedHeap));
                                currentPercentHeap = -1;
                                minorGCDuration = -1;
                                fullGCDuration = -1;
                            } else {
                                future = _session.writeAndFlush(new Message(Constants.WRAPPER_MSG_PING, ""));
                            }
                        }
                        try {
                            future.await(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        start = System.currentTimeMillis();
                    } else if ((_haltAppOnWrapper && (System.currentTimeMillis() - start) > _startupTimeout)
                            && !_stopping) {
                        System.out.println("no connection to wrapper during " + (_startupTimeout / 1000)
                                + " seconds -> System.exit(-1)");
                        System.out.println(
                                "if this is due to server overload consider increasing yajsw configuration property wrapper.startup.timeout");
                        System.exit(-1);
                    }
                }
            });
    _pinger.start();

    // connect
    // handler should process messages in a separate thread

    reconnect();
    /*
     * try { if (_config.getInt("wrapper.action.port") > 0) { _actionHandler
     * = new ActionHandler(this, _config); _actionHandler.start(); } } catch
     * (Exception ex) { log.info("could not start action handler " +
     * ex.getMessage()); }
     */

}

From source file:org.rzo.yajsw.app.WrapperManagerImpl.java

License:Apache License

/**
 * Reconnect./* www  . j ava2s . c  om*/
 */
private void reconnect() {
    // try connecting, if we could not sleep then retry
    while (!_started) {
        if (_debug > 1)
            // log.fine("connecting to port " + _port);
            System.out.println("connecting to port " + _port);
        final ChannelFuture future1 = connector.connect();
        try {
            Thread.yield();
            // System.out.println("connecting wait future ");
            future1.await(10000);
            // System.out.println("after connecting wait future ");
            _started = future1.isSuccess();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            System.out.println("error connecting to wrapper: " + e1);
            e1.printStackTrace();
        }
        /*
         * executor.execute(new Runnable() {
         * 
         * public void run() { future1.addListener(new
         * ChannelFutureListener() { public void
         * operationComplete(ChannelFuture future) throws Exception {
         * _lock.lock(); System.out.println("future" + future.isSuccess());
         * _started = future.isSuccess(); _connectEnd.signal();
         * _lock.unlock();
         * 
         * } }); }
         * 
         * });
         * 
         * _lock.lock(); try { _connectEnd.await(); } catch
         * (InterruptedException e1) { // TODO Auto-generated catch block
         * e1.printStackTrace(); } _lock.unlock();
         * System.out.println("started "+_started);
         */

        if (_started) {
            if (_debug > 2)
                System.out.println("WrapperManager: channel connected, sending key");
            future1.channel().writeAndFlush(new Message(Constants.WRAPPER_MSG_KEY, _key));
        } else
            try {
                if (_debug > 0)
                    // log.fine("connection failed -> sleep then retry");
                    System.out.println("connection failed -> sleep then retry");
                _started = false;
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }
}

From source file:org.rzo.yajsw.controller.jvm.JVMController.java

License:Apache License

public synchronized void closeChannel() {
    if (_channel.get() != null && _channel.get().isOpen())
        try {/*from   w  ww . j  a v a2  s.c o  m*/
            ChannelFuture cf = _channel.get().close();
            Thread.yield();
            if (getDebug() > 1)
                getLog().info("controller close session");
            cf.await(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            getLog().info("session close wait interrupted in JVMController");
        }
    // stop processing outgoing messages
    // _controller.workerExecutor.shutdownNow();

    // stop the controller
    _channel.set(null);
    setState(JVMController.STATE_WAITING_CLOSED);
    if (getDebug() > 2)
        getLog().info("session closed -> waiting");
}