Example usage for io.netty.channel ChannelFutureListener ChannelFutureListener

List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener

Introduction

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

Prototype

ChannelFutureListener

Source Link

Usage

From source file:com.dinstone.netty.Client.java

License:Apache License

public static void main(String[] args) throws IOException, InterruptedException {
    Bootstrap b = new Bootstrap();
    b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<NioSocketChannel>() {

                @Override//from  w  w  w .  j a  va  2s.co m
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast("dd", new ChannelHandlerAdapter() {

                        /**
                         * {@inheritDoc}
                         * 
                         * @see io.netty.channel.ChannelHandlerAdapter#exceptionCaught(io.netty.channel.ChannelHandlerContext,
                         *      java.lang.Throwable)
                         */
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                throws Exception {
                            System.out.println("error: ");
                            cause.printStackTrace();
                        }
                    });
                }
            });
    b.connect("localhost", 8090).addListener(new ChannelFutureListener() {

        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                future.channel().write(Unpooled.buffer().writeBytes("123".getBytes()));
                future.channel().flush();
            }
        }
    });
}

From source file:com.diwayou.hybrid.remoting.netty.NettyRemotingAbstract.java

License:Apache License

public RemotingCommand invokeSyncImpl(final Channel channel, final RemotingCommand request,
        final long timeoutMillis)
        throws InterruptedException, RemotingSendRequestException, RemotingTimeoutException {
    try {//from   w w w  .j  a  va 2  s  .  c o m
        final ResponseFuture responseFuture = new ResponseFuture(request.getOpaque(), timeoutMillis, null,
                null);
        this.responseTable.put(request.getOpaque(), responseFuture);
        channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture f) throws Exception {
                if (f.isSuccess()) {
                    responseFuture.setSendRequestOK(true);
                    return;
                } else {
                    responseFuture.setSendRequestOK(false);
                }

                responseTable.remove(request.getOpaque());
                responseFuture.setCause(f.cause());
                responseFuture.putResponse(null);
                plog.warn("send a request command to channel <" + channel.remoteAddress() + "> failed.");
                plog.warn(request.toString());
            }
        });

        RemotingCommand responseCommand = responseFuture.waitResponse(timeoutMillis);
        if (null == responseCommand) {
            // ????
            if (responseFuture.isSendRequestOK()) {
                throw new RemotingTimeoutException(RemotingHelper.parseChannelRemoteAddr(channel),
                        timeoutMillis, responseFuture.getCause());
            }
            // ??
            else {
                throw new RemotingSendRequestException(RemotingHelper.parseChannelRemoteAddr(channel),
                        responseFuture.getCause());
            }
        }

        return responseCommand;
    } finally {
        this.responseTable.remove(request.getOpaque());
    }
}

From source file:com.dwarf.netty.guide.factorial.FactorialClientHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, final BigInteger msg) {
    receivedMessages++;// www  . jav a  2s  . com
    if (receivedMessages == FactorialClient.COUNT) {
        // Offer the answer after closing the connection.
        ctx.channel().close().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                boolean offered = answer.offer(msg);
                assert offered;
            }
        });
    }
}

From source file:com.emin.igwmp.skm.core.netty.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// w  w  w.  j a  va2  s  .co 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 {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else {
        ctx.close();
    }
}

From source file:com.emin.igwmp.skm.core.netty.SocksServer.java

License:Apache License

/**
 * ?socket?/*from   ww w  .j ava  2  s .  c o  m*/
 * */
public void startServer() {
    mServerBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(mSocksServerInitializer);

    try {
        //            mServerBootstrap.bind(PORT).sync().channel().closeFuture().sync();
        mChannelFuture = mServerBootstrap.bind(PORT).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    final EventLoop loop = future.channel().eventLoop();
                    loop.schedule(new Runnable() {
                        @Override
                        public void run() {
                            startServer();
                        }

                    }, 1L, TimeUnit.SECONDS);

                }
            }
        }).sync();
        mChannelFuture.channel().closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
        stopServer();
    }

}

From source file:com.eucalyptus.util.async.AsyncRequestHandler.java

License:Open Source License

/**
 *
 *//*from  ww w . jav  a2  s .co m*/
@Override
public boolean fire(final ServiceConfiguration config, final Q request) {
    if (!this.request.compareAndSet(null, request)) {
        LOG.warn("Duplicate write attempt for request: " + this.request.get().getClass().getSimpleName());
        return false;
    } else {
        try {
            final InetSocketAddress serviceSocketAddress = config.getSocketAddress();
            final Bootstrap clientBootstrap = config.getComponentId().getClientBootstrap();
            final ChannelInitializer<?> initializer = config.getComponentId().getClientChannelInitializer();
            final int poolSizeLimit = initializer instanceof AsyncRequestPoolable
                    ? ((AsyncRequestPoolable) initializer).fixedSize()
                    : -1;
            final IoMessage<FullHttpRequest> ioMessage = IoMessage.httpRequest(ServiceUris.internal(config),
                    this.request.get());
            final ChannelPoolKey poolKey = new ChannelPoolKey(clientBootstrap, initializer,
                    serviceSocketAddress, poolSizeLimit);
            final long before = System.currentTimeMillis();
            this.channelPool = POOL_MAP.get(poolKey);
            this.acquireFuture = channelPool.acquire();
            this.acquireFuture.addListener(new GenericFutureListener<Future<Channel>>() {
                @Override
                public void operationComplete(final Future<Channel> future) throws Exception {
                    try {
                        if (future.isSuccess()) {
                            final Channel channel = future.get();
                            logAcquired(channel, before);
                            channel.pipeline().addLast("request-handler", AsyncRequestHandler.this);

                            if (!initializer.getClass().getSimpleName().startsWith("GatherLog")) {
                                Topology.populateServices(config, AsyncRequestHandler.this.request.get());
                            }

                            logMessage(ioMessage);

                            channel.writeAndFlush(ioMessage).addListener(new ChannelFutureListener() {
                                @Override
                                public void operationComplete(final ChannelFuture future) throws Exception {
                                    AsyncRequestHandler.this.writeComplete.set(true);

                                    Logs.extreme()
                                            .debug(EventRecord.here(request.getClass(),
                                                    EventClass.SYSTEM_REQUEST, EventType.CHANNEL_WRITE,
                                                    request.getClass().getSimpleName(),
                                                    request.getCorrelationId(), serviceSocketAddress.toString(),
                                                    "" + future.channel().localAddress(),
                                                    "" + future.channel().remoteAddress()));
                                }
                            });
                        } else {
                            AsyncRequestHandler.this.teardown(future.cause());
                        }
                    } catch (final Exception ex) {
                        LOG.error(ex, ex);
                        AsyncRequestHandler.this.teardown(ex);
                    }
                }
            });
            return true;
        } catch (final Exception t) {
            LOG.error(t, t);
            this.teardown(t);
            return false;
        }
    }
}

From source file:com.eucalyptus.util.async.AsyncRequestHandler.java

License:Open Source License

private void closeAndReleaseChannel(@Nonnull final Channel channel) {
    if (channel.isOpen()) {
        channel.close().addListener(new ChannelFutureListener() {
            @Override//from w  w w.  ja v a 2  s.co  m
            public void operationComplete(final ChannelFuture future) throws Exception {
                EventRecord.here(AsyncRequestHandler.this.request.get().getClass(), EventClass.SYSTEM_REQUEST,
                        EventType.CHANNEL_CLOSED).trace();
                releaseChannel(channel);
            }
        });
    } else {
        EventRecord.here(AsyncRequestHandler.this.request.get().getClass(), EventClass.SYSTEM_REQUEST,
                EventType.CHANNEL_CLOSED, "ALREADY_CLOSED").trace();
        releaseChannel(channel);
    }
}

From source file:com.feihong.newzxclient.tcp.NettyClient.java

License:Apache License

@SuppressWarnings("unchecked")
public void connect() throws Exception {
    mGroup = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(mGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override//from www  .j  a v  a  2s. c o m
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("decoder", new IntLengthDecoder());
                    ch.pipeline().addLast(new NettyClientHandler());
                }
            });

    ChannelFuture future = b.connect(host, port).sync();
    future.addListeners(new ChannelFutureListener() {
        public void operationComplete(final ChannelFuture future) throws Exception {
            requestLogin();
        }
    });

    mChannel = future.channel();

    mHandler = mChannel.pipeline().get(NettyClientHandler.class);

}

From source file:com.fjn.helper.frameworkex.netty.v4.discardserver.DiscardServerHandler.java

License:Apache License

/**
 * ???/*from   ww  w .j av  a 2  s . com*/
 * @param ctx
 * @param msg
 * @throws Exception
 */
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;
    try {
        while (in.isReadable()) {
            char c = (char) in.readByte();
            content += c;
            if (c == '\n' || c == '\r') {
                if (!line.isEmpty()) {
                    System.out.println(line);
                }
                if ("quit".equals(line)) {
                    ByteBuf bf = ctx.alloc().buffer(content.getBytes().length);
                    bf.setBytes(0, content.getBytes());
                    final ChannelFuture f = ctx.writeAndFlush(bf); // (3)
                    f.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws InterruptedException {
                            assert f == future;
                            ctx.close();
                        }
                    }); // (4)
                }
                line = "";
                continue;
            } else {
                line += c;
            }
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.flysoloing.learning.network.netty.factorial.FactorialClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, final BigInteger msg) {
    receivedMessages++;//from   ww w.j a va2s . c o m
    if (receivedMessages == FactorialClient.COUNT) {
        // Offer the answer after closing the connection.
        ctx.channel().close().addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) {
                boolean offered = answer.offer(msg);
                assert offered;
            }
        });
    }
}