Example usage for io.netty.channel ChannelFuture addListener

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

Introduction

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

Prototype

@Override
    ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);

Source Link

Usage

From source file:com.mastfrog.scamper.Sender.java

License:Open Source License

/**
 * Send a message using the passed channel.
 *
 * @param address The address//from   ww w  . j a  va 2s. co  m
 * @param message A future which will be notified when the message is
 * flushed to the socket
 * @param sctpChannel The ordinal of the sctp channel
 * @param l A ChannelFutureListener to be notified when the mesage is
 * flushed (remember to check <code>ChannelFuture.getCause()</code> to check
 * for failure)
 * @return a future that will be notified when the message write is
 * completed
 */
public ChannelFuture send(final Address address, final Message<?> message, final int sctpChannel,
        final ChannelFutureListener l) {
    Checks.notNull("address", address);
    Checks.notNull("message", message);
    Checks.nonNegative("sctpChannel", sctpChannel);
    logger.log(Level.FINE, "Send message to {0} on {1} type {1}",
            new Object[] { address, sctpChannel, message.type });
    return associations.connect(address).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.cause() == null) {
                logger.log(Level.FINE, "Got back connection {0} for {1}",
                        new Object[] { future.channel().remoteAddress(), address });
            }
            ChannelFuture fut = send(future.channel(), message, sctpChannel);
            if (l != null) {
                fut.addListener(l);
            }
        }
    });
}

From source file:com.mongodb.connection.netty.NettyStream.java

License:Apache License

@Override
public void openAsync(final AsyncCompletionHandler<Void> handler) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup);/*w  ww.  j ava2s. c  o  m*/
    bootstrap.channel(NioSocketChannel.class);

    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, settings.getConnectTimeout(MILLISECONDS));
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, settings.isKeepAlive());

    if (settings.getReceiveBufferSize() > 0) {
        bootstrap.option(ChannelOption.SO_RCVBUF, settings.getReceiveBufferSize());
    }
    if (settings.getSendBufferSize() > 0) {
        bootstrap.option(ChannelOption.SO_SNDBUF, settings.getSendBufferSize());
    }
    bootstrap.option(ChannelOption.ALLOCATOR, allocator);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(final SocketChannel ch) throws Exception {
            if (sslSettings.isEnabled()) {
                SSLEngine engine = SSLContext.getDefault().createSSLEngine(address.getHost(),
                        address.getPort());
                engine.setUseClientMode(true);
                if (!sslSettings.isInvalidHostNameAllowed()) {
                    engine.setSSLParameters(enableHostNameVerification(engine.getSSLParameters()));
                }
                ch.pipeline().addFirst("ssl", new SslHandler(engine, false));
            }
            ch.pipeline().addLast("readTimeoutHandler",
                    new ReadTimeoutHandler(settings.getReadTimeout(MILLISECONDS), MILLISECONDS));
            ch.pipeline().addLast(new InboundBufferHandler());
        }
    });
    final ChannelFuture channelFuture = bootstrap.connect(address.getHost(), address.getPort());
    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = channelFuture.channel();
                handler.completed(null);
            } else {
                handler.failed(future.cause());
            }
        }
    });
}

From source file:com.mpush.client.gateway.connection.GatewayTCPConnectionFactory.java

License:Apache License

private void addConnection(String host, int port, boolean sync) {
    ChannelFuture future = client.connect(host, port);
    future.channel().attr(attrKey).set(getHostAndPort(host, port));
    future.addListener(f -> {
        if (!f.isSuccess()) {
            logger.error("create gateway connection ex, host={}, port={}", host, port, f.cause());
        }/*from  ww  w  .  j  av  a2s  . com*/
    });
    if (sync)
        future.awaitUninterruptibly();
}

From source file:com.mpush.core.handler.AdminHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
    Command command = Command.help;/*from   w  w w .  j a v  a  2s  . c om*/
    String arg = null;
    String[] args = null;
    if (request != null) {
        String[] cmd_args = request.split(" ");
        command = Command.toCmd(cmd_args[0].trim());
        if (cmd_args.length == 2) {
            arg = cmd_args[1];
        } else if (cmd_args.length > 2) {
            args = Arrays.copyOfRange(cmd_args, 1, cmd_args.length);
        }
    }
    try {
        Object result = args != null ? command.handler(ctx, args) : command.handler(ctx, arg);
        ChannelFuture future = ctx.writeAndFlush(result + EOL + EOL);
        if (command == Command.quit) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    } catch (Throwable throwable) {
        ctx.writeAndFlush(throwable.getLocalizedMessage() + EOL + EOL);
        StringWriter writer = new StringWriter(1024);
        throwable.printStackTrace(new PrintWriter(writer));
        ctx.writeAndFlush(writer.toString());
    }
    LOGGER.info("receive admin command={}", request);
}

From source file:com.mpush.netty.client.NettyClient.java

License:Apache License

@Override
public void start(final Listener listener) {
    if (started.compareAndSet(false, true)) {
        Bootstrap bootstrap = new Bootstrap();
        workerGroup = new NioEventLoopGroup();
        bootstrap.group(workerGroup)//
                .option(ChannelOption.TCP_NODELAY, true)//
                .option(ChannelOption.SO_REUSEADDR, true)//
                .option(ChannelOption.SO_KEEPALIVE, true)//
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
                .channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);

        bootstrap.handler(new ChannelInitializer<SocketChannel>() { // (4)
            @Override//from   w ww.j a  v  a 2  s.c o m
            public void initChannel(SocketChannel ch) throws Exception {
                initPipeline(ch.pipeline());
            }
        });

        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    if (listener != null)
                        listener.onSuccess(port);
                    LOGGER.info("start netty client success, host={}, port={}", host, port);
                } else {
                    if (listener != null)
                        listener.onFailure(future.cause());
                    LOGGER.error("start netty client failure, host={}, port={}", host, port, future.cause());
                }
            }
        });
    } else {
        listener.onFailure(new ServiceException("client has started!"));
    }
}

From source file:com.mpush.netty.connection.NettyConnection.java

License:Apache License

@Override
public ChannelFuture send(Packet packet, final ChannelFutureListener listener) {
    if (channel.isActive()) {

        ChannelFuture future = channel.writeAndFlush(packet.toFrame(channel)).addListener(this);

        if (listener != null) {
            future.addListener(listener);
        }//from w w w.ja va 2s .  c  om

        if (channel.isWritable()) {
            return future;
        }

        //
        //return channel.newPromise().setFailure(new RuntimeException("send data too busy"));
        if (!future.channel().eventLoop().inEventLoop()) {
            future.awaitUninterruptibly(100);
        }
        return future;
    } else {
        /*if (listener != null) {
        channel.newPromise()
                .addListener(listener)
                .setFailure(new RuntimeException("connection is disconnected"));
        }*/
        return this.close();
    }
}

From source file:com.mpush.netty.http.NettyHttpClient.java

License:Apache License

@Override
public void request(RequestContext context) throws Exception {
    URI uri = new URI(context.request.uri());
    String host = context.host = uri.getHost();
    int port = uri.getPort() == -1 ? 80 : uri.getPort();
    //1.//www  . j av a 2 s  .  c o m
    context.request.headers().set(HOST, host);//?host
    context.request.headers().set(CONNECTION, KEEP_ALIVE);//?

    //2.
    timer.newTimeout(context, context.readTimeout, TimeUnit.MILLISECONDS);

    //3.?????
    Channel channel = pool.tryAcquire(host);
    if (channel == null) {
        final long startCreate = System.currentTimeMillis();
        LOGGER.debug("create new channel, host={}", host);
        ChannelFuture f = b.connect(host, port);
        f.addListener((ChannelFutureListener) future -> {
            LOGGER.debug("create new channel cost={}", (System.currentTimeMillis() - startCreate));
            if (future.isSuccess()) {//3.1.http server
                writeRequest(future.channel(), context);
            } else {//3.2
                context.tryDone();
                context.onFailure(504, "Gateway Timeout");
                LOGGER.warn("create new channel failure, request={}", context);
            }
        });
    } else {
        //3.1.http server
        writeRequest(channel, context);
    }
}

From source file:com.mpush.test.client.ConnClientBoot.java

License:Apache License

public ChannelFuture connect(InetSocketAddress remote, InetSocketAddress local, ClientConfig clientConfig) {
    ChannelFuture future = local != null ? bootstrap.connect(remote, local) : bootstrap.connect(remote);
    if (future.channel() != null)
        future.channel().attr(CONFIG_KEY).set(clientConfig);
    future.addListener(f -> {
        if (f.isSuccess()) {
            future.channel().attr(CONFIG_KEY).set(clientConfig);
            LOGGER.info("start netty client success, remote={}, local={}", remote, local);
        } else {//from www.  j  a  v  a2s.  co m
            LOGGER.error("start netty client failure, remote={}, local={}", remote, local, f.cause());
        }
    });
    return future;
}

From source file:com.mycompany.device.FFDevice.java

public FFDevice(SocketChannel ch) {
    this.req = null;
    this.soc = ch;
    this.data_rcv = soc.alloc().buffer(512);
    this.reg_str = "";
    this.connect_time = System.currentTimeMillis();

    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(new IdleStateHandler(0, 0, idle_time_interval_s));
    pipeline.addLast(new MessageToByteEncoder<byte[]>() {
        @Override//from  w w w .  ja  v a  2  s . c  om
        protected void encode(ChannelHandlerContext ctx, byte[] msg, ByteBuf out) throws Exception {
            // TODO Auto-generated method stub
            out.writeBytes(msg);
        }
    });
    pipeline.addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            // TODO Auto-generated method stub
            ByteBuf bb = (ByteBuf) msg;
            if (reg_str.equals("")) {
                reg_str = bb.toString(Charset.defaultCharset());
                FFServer.logger.info(String.format("device that has regs %s is registed", reg_str));
            } else {
                FFServer.logger.debug(String.format("%s receive: %d bytes", reg_str, bb.readableBytes()));
                data_rcv.writeBytes(bb);
            }
            ReferenceCountUtil.release(msg);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            // TODO Auto-generated method stub
            FFServer.logger.error(cause);
            Close();
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent event = (IdleStateEvent) evt;
                if (event.state() == IdleState.ALL_IDLE) {
                    FFServer.logger.info(String.format("%s in idle state", reg_str));

                    ByteBuf hb = ctx.alloc().buffer(1).writeByte('.');
                    Send(hb);
                }
            }
        }
    });

    ChannelFuture f = soc.closeFuture();
    f.addListener((ChannelFutureListener) new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            is_closed = true;
            FFServer.logger.info(String.format("%s disconnected", reg_str));
        }
    });
}

From source file:com.netty.fileTest.file.FileSenderServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    String filePath = "c:\\abc.msi";
    RandomAccessFile raf = null;/*  w ww. j a  v a  2 s. c  o  m*/
    long length = -1;
    try {
        raf = new RandomAccessFile(filePath, "r");
        length = raf.length();
    } catch (Exception e) {
        ctx.writeAndFlush("ERR: " + e.getClass().getSimpleName() + ": " + e.getMessage() + '\n');
        return;
    } finally {
        if (length < 0 && raf != null) {
            raf.close();
        }
    }

    ctx.write("OK: " + raf.length() + '\n');

    // SSL not enabled - can use zero-copy file transfer.
    ChannelFuture writeFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, length));
    writeFuture.addListener(new ChannelProgressiveFutureListener() {

        @Override
        public void operationComplete(ChannelProgressiveFuture future) throws Exception {
            System.out.printf("file sender completed!");
        }

        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total)
                throws Exception {
            System.out.printf("now:" + progress + " total:" + total);

        }
    });

    ctx.writeAndFlush("\n");
}