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.github.mrstampy.kitchensync.netty.channel.AbstractKiSyChannel.java

License:Open Source License

@Override
public ChannelFuture close() {
    if (!isActive())
        return new KiSyFailedFuture();

    ChannelFuture cf = getChannel().close();
    cf.addListener(CLOSE_FUTURE);

    return cf;/* w ww  .j a  v a 2 s  .  co  m*/
}

From source file:com.github.mrstampy.kitchensync.netty.channel.AbstractKiSyChannel.java

License:Open Source License

/**
 * Close channel./*  ww w .j  a  v  a 2  s  .c  o m*/
 */
protected void closeChannel() {
    ChannelFuture cf = close();
    final CountDownLatch latch = new CountDownLatch(1);
    cf.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            latch.countDown();
        }
    });

    await(latch, "Channel close timed out");
}

From source file:com.github.mrstampy.kitchensync.netty.channel.AbstractKiSyMulticastChannel.java

License:Open Source License

@Override
public boolean joinGroup() {
    if (!isActive())
        return false;

    ChannelFuture cf = getChannel().joinGroup(getMulticastAddress(), getNetworkInterface());

    CountDownLatch latch = new CountDownLatch(1);
    cf.addListener(getJoinGroupListener(getMulticastAddress(), latch));

    await(latch, "Multicast channel join group timed out");

    return cf.isSuccess();
}

From source file:com.github.mrstampy.kitchensync.netty.channel.AbstractKiSyMulticastChannel.java

License:Open Source License

@Override
public boolean leaveGroup() {
    if (!isActive())
        return false;

    ChannelFuture cf = getChannel().leaveGroup(getMulticastAddress(), getNetworkInterface());

    CountDownLatch latch = new CountDownLatch(1);
    cf.addListener(getLeaveGroupListener(getMulticastAddress(), latch));

    await(latch, "Multicast channel leave group timed out");

    return cf.isSuccess();
}

From source file:com.github.mrstampy.kitchensync.netty.channel.AbstractKiSyMulticastChannel.java

License:Open Source License

@Override
public boolean block(InetAddress sourceToBlock) {
    if (!isActive())
        return false;

    ChannelFuture cf = getChannel().block(getMulticastAddress().getAddress(), getNetworkInterface(),
            sourceToBlock);/*from   w w  w . java  2 s. c o m*/

    CountDownLatch latch = new CountDownLatch(1);
    cf.addListener(getBlockListener(getMulticastAddress(), latch, sourceToBlock));

    await(latch, "Multicast block timed out");

    return cf.isSuccess();
}

From source file:com.github.mrstampy.kitchensync.stream.AbstractStreamer.java

License:Open Source License

/**
 * Writes the bytes to the {@link #getChannel()}. Invoked from
 * {@link #processChunk(byte[])}, override if necessary.
 *
 * @param chunk//from   w w  w .  jav  a 2 s  . co m
 *          the chunk
 */
protected void sendChunk(byte[] chunk) {
    if (isAckRequired())
        ackKeys.add(StreamerAckRegister.add(chunk, this));

    ChannelFuture cf = channel.send(chunk, destination);

    if (isFullThrottle())
        cf.addListener(streamerListener);

    sent.addAndGet(chunk.length - getEffectiveChunkProcessor().sizeInBytes(this));
}

From source file:com.github.mrstampy.kitchensync.stream.AbstractStreamer.java

License:Open Source License

/**
 * Implementation method to send an end of message message.
 * //from w ww .  j  a va  2  s  . c  o  m
 * @see EndOfMessageRegister
 * @see EndOfMessageInboundMessageHandler
 * @see EndOfMessageListener
 * @see #isEomOnFinish()
 * @see #setEomOnFinish(boolean)
 * @see #setFooter(Footer)
 */
public void sendEndOfMessage() {
    await(latch, 100, TimeUnit.MILLISECONDS);
    latch = new CountDownLatch(1);
    ChannelFuture cf = channel.send(getFooter().createFooter(), destination);
    cf.addListener(streamerListener);
    await(latch, 50, TimeUnit.MILLISECONDS);
}

From source file:com.github.mrstampy.kitchensync.test.AbstractTester.java

License:Open Source License

/**
 * Adds the latch listener.//from ww  w  .  ja  v  a2  s .c  o  m
 *
 * @param cf
 *          the cf
 * @param cdl
 *          the cdl
 */
protected void addLatchListener(ChannelFuture cf, final CountDownLatch cdl) {
    cf.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            cdl.countDown();
        }
    });
}

From source file:com.github.mrstampy.kitchensync.test.BroadcastTester.java

License:Open Source License

/**
 * Execute.//  w ww  .j  a  v  a 2  s  . co m
 */
public void execute() {
    michael.leaveGroup();

    ChannelFuture cf = michael.broadcast("A good day to you all!");

    cf.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            michael.joinGroup();
        }
    });
}

From source file:com.github.netfreer.shadowducks.client.handler.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
    if (message instanceof Socks4CommandRequest) {
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override//from   w  w w . j a v  a 2  s  . c o  m
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CommandRequest) {
        final Socks5CommandRequest request = (Socks5CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS,
                                    request.dstAddrType(), request.dstAddr(), request.dstPort()));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));
        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Attribute<Long> beginTimeAttr = ctx.channel().attr(AttrKeys.CHANNEL_BEGIN_TIME);
                final long parseTime = beginTimeAttr.get();
                long usedTime = System.currentTimeMillis() - parseTime;
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                    logger.info("connect {}:{} success, use time {} millis.", request.dstAddr(),
                            request.dstPort(), usedTime);
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                    logger.info("connect {}:{} failure, use time {} millis.", request.dstAddr(),
                            request.dstPort(), usedTime);
                }
                beginTimeAttr.set(null);
            }
        });
    } else {
        ctx.close();
    }
}