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.alibaba.dubbo.remoting.transport.netty.NettyChannel.java

License:Apache License

public void send(Object message, boolean sent) throws RemotingException {
    super.send(message, sent);

    boolean success = true;
    int timeout = 0;
    try {//w ww  . j av a  2s  .  c om
        ChannelFuture future = channel.writeAndFlush(message);
        if (sent) {
            timeout = getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT);
            success = future.await(timeout);
        }
        future.sync();
        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:com.alibaba.dubbo.remoting.transport.netty4.NettyChannel.java

License:Apache License

public void send(Object message, boolean sent) throws RemotingException {
    super.send(message, sent);

    boolean success = true;
    int timeout = 0;
    try {//from  w w  w.  j a va2  s .co  m
        ChannelFuture future = channel.writeAndFlush(message);
        if (sent) {
            timeout = getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.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:com.amebame.triton.service.lock.LockOwner.java

License:Creative Commons License

/**
 * Send ready to the owner client.// w ww  .  ja  va  2 s .co m
 * @return
 */
public boolean sendReady() {
    TritonMessage message = new TritonMessage(TritonMessage.REPLY, callId, ownerId);
    if (!channel.isOpen()) {
        return false;
    }
    ChannelFuture future = channel.writeAndFlush(message);
    try {
        if (future.await(1000L)) {
            return future.isSuccess();
        }
    } catch (InterruptedException e) {
    }
    return false;
}

From source file:com.amebame.triton.service.lock.LockOwner.java

License:Creative Commons License

/**
 * Send fail to the owner client./*from   w w  w.j  ava2s  .c  o  m*/
 * @return
 */
public boolean sendFail() {
    if (!channel.isWritable()) {
        return false;
    }
    TritonMessage message = new TritonMessage(TritonMessage.REPLY, callId, -1);
    ChannelFuture future = channel.writeAndFlush(message);
    try {
        if (future.await(1000L)) {
            return future.isSuccess();
        }
    } catch (InterruptedException e) {
    }
    return false;
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppClient.java

License:Apache License

protected Channel createConnectedChannel(String host, int port, long connectTimeoutMillis)
        throws SmppTimeoutException, SmppChannelException, InterruptedException {
    // a socket address used to "bind" to the remote system
    InetSocketAddress socketAddr = new InetSocketAddress(host, port);

    // attempt to connect to the remote system
    ChannelFuture connectFuture = this.clientBootstrap.connect(socketAddr);

    // wait until the connection is made successfully
    boolean timeout = !connectFuture.await(connectTimeoutMillis);

    if (timeout) {
        throw new SmppChannelConnectTimeoutException("Unable to connect to host [" + host + "] and port ["
                + port + "] within " + connectTimeoutMillis + " ms");
    }//from www  . ja va  2  s. co m

    if (!connectFuture.isSuccess()) {
        throw new SmppChannelConnectException("Unable to connect to host [" + host + "] and port [" + port
                + "]: " + connectFuture.cause().getMessage(), connectFuture.cause());
    }

    // if we get here, then we were able to connect and get a channel
    return connectFuture.channel();
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppServer.java

License:Apache License

@Override
public void start() throws SmppChannelException {
    if (isDestroyed()) {
        throw new SmppChannelException("Unable to start: server is destroyed");
    }/*from  w w w  .  j a v  a 2s .com*/
    try {
        ChannelFuture f = this.serverBootstrap.bind(new InetSocketAddress(configuration.getPort()));

        // wait until the connection is made successfully
        boolean timeout = !f.await(configuration.getBindTimeout());

        if (timeout || !f.isSuccess())
            throw new SmppChannelException("Can't bind to port " + configuration.getPort() + " after "
                    + configuration.getBindTimeout() + " milliseconds");

        logger.info("{} started on SMPP port [{}]", configuration.getName(), configuration.getPort());
        serverChannel = f.channel();
    } catch (ChannelException e) {
        throw new SmppChannelException(e.getMessage(), e);
    } catch (InterruptedException e) {
        throw new SmppChannelException(e.getMessage(), e);
    }
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppSession.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/* ww w  . j  a  v  a2  s.  c  om*/
public WindowFuture<Integer, PduRequest, PduResponse> sendRequestPdu(PduRequest pdu, long timeoutMillis,
        boolean synchronous) throws RecoverablePduException, UnrecoverablePduException, SmppTimeoutException,
        SmppChannelException, InterruptedException {
    // assign the next PDU sequence # if its not yet assigned
    if (!pdu.hasSequenceNumberAssigned()) {
        pdu.setSequenceNumber(this.sequenceNumber.next());
    }

    // encode the pdu into a buffer
    ByteBuf buffer = transcoder.encode(pdu);

    WindowFuture<Integer, PduRequest, PduResponse> future = null;
    try {
        future = sendWindow.offer(pdu.getSequenceNumber(), pdu, timeoutMillis,
                configuration.getRequestExpiryTimeout(), synchronous);
    } catch (DuplicateKeyException e) {
        throw new UnrecoverablePduException(e.getMessage(), e);
    } catch (OfferTimeoutException e) {
        throw new SmppTimeoutException(e.getMessage(), e);
    }

    // we need to log the PDU after encoding since some things only happen
    // during the encoding process such as looking up the result message
    if (configuration.getLoggingOptions().isLogPduEnabled()) {
        if (synchronous) {
            logger.info("sync send PDU: {}", pdu);
        } else {
            logger.info("async send PDU: {}", pdu);
        }
    }

    // write the pdu out & wait timeout amount of time
    ChannelFuture channelFuture = this.channel.writeAndFlush(buffer);
    if (configuration.getWriteTimeout() > 0) {
        channelFuture.await(configuration.getWriteTimeout());
    } else {
        channelFuture.await();
    }

    // check if the write was a success
    if (!channelFuture.isSuccess()) {
        // the write failed, make sure to throw an exception
        throw new SmppChannelException(channelFuture.cause().getMessage(), channelFuture.cause());
    }

    this.countSendRequestPdu(pdu);

    return future;
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppSession.java

License:Apache License

/**
 * Asynchronously sends a PDU and does not wait for a response PDU.
 * This method will wait for the PDU to be written to the underlying channel.
 * @param pdu The PDU to send (can be either a response or request)
 * @throws RecoverablePduException//from ww  w .  j av  a  2s . c om
 * @throws UnrecoverablePduException
 * @throws SmppChannelException
 * @throws InterruptedException
 */
@Override
public void sendResponsePdu(PduResponse pdu)
        throws RecoverablePduException, UnrecoverablePduException, SmppChannelException, InterruptedException {
    // assign the next PDU sequence # if its not yet assigned
    if (!pdu.hasSequenceNumberAssigned()) {
        pdu.setSequenceNumber(this.sequenceNumber.next());
    }

    // encode the pdu into a buffer
    ByteBuf buffer = transcoder.encode(pdu);

    // we need to log the PDU after encoding since some things only happen
    // during the encoding process such as looking up the result message
    if (configuration.getLoggingOptions().isLogPduEnabled()) {
        logger.info("send PDU: {}", pdu);
    }

    // write the pdu out & wait timeout amount of time
    ChannelFuture channelFuture = this.channel.writeAndFlush(buffer);
    if (configuration.getWriteTimeout() > 0) {
        channelFuture.await(configuration.getWriteTimeout());
    } else {
        channelFuture.await();
    }

    // check if the write was a success
    if (!channelFuture.isSuccess()) {
        // the write failed, make sure to throw an exception
        throw new SmppChannelException(channelFuture.cause().getMessage(), channelFuture.cause());
    }
}

From source file:com.qq.servlet.demo.netty.telnet.client.ClientHandler.java

License:Apache License

@Override
protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
    Channel ch = ctx.channel();/*from w w  w .ja  v  a  2  s . c  om*/
    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:com.qq.servlet.demo.netty.telnet.TelnetClientHandler.java

License:Apache License

@Override
protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
    Channel ch = ctx.channel();/*www  . j  a v  a2s. c  o  m*/
    AttributeKey<AsyncContext> key = AttributeKey.valueOf("ASYNC_CONTEXT");
    Attribute<AsyncContext> attr = ch.attr(key);
    AsyncContext context = attr.get();

    if (context != null) {
        HttpServletRequest request = (HttpServletRequest) context.getRequest();
        HttpServletResponse response = (HttpServletResponse) context.getResponse();
        Object object = request.getAttribute("beginTime");
        long bt = Long.parseLong(object.toString());
        PrintWriter writer = response.getWriter();
        writer.println("invoke api result: \t");
        long time = System.currentTimeMillis() - bt;
        //         writer.println("???"+time);
        writer.flush();
        //servlet?http?
        System.err.println(context + "\t" + request.getAttribute("REQUEST_ID"));
        context.complete();
    } else {
        System.out.println(context + "----------->" + msg);
    }
    ChannelFuture future = ch.close();
    future.await(100);
}