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:org.jupiter.transport.netty.channel.NettyChannel.java

License:Apache License

@Override
public JChannel write(Object msg, final JFutureListener<JChannel> listener) {
    final JChannel jChannel = this;
    channel.writeAndFlush(msg).addListener(new ChannelFutureListener() {

        @Override/*from   www  .  ja  v a2 s . c om*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                listener.operationSuccess(jChannel);
            } else {
                listener.operationFailure(jChannel, future.cause());
            }
        }
    });
    return jChannel;
}

From source file:org.jupiter.transport.netty.handler.connector.ConnectionWatchdog.java

License:Apache License

@Override
public void run(Timeout timeout) throws Exception {
    if (!isReconnectNeeded()) {
        logger.warn("Cancel reconnecting with {}.", remoteAddress);
        return;/*w w w. j a va  2 s . c  o m*/
    }

    ChannelFuture future;
    synchronized (bootstrap) {
        bootstrap.handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(handlers());
            }
        });
        future = bootstrap.connect(remoteAddress);
    }

    future.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture f) throws Exception {
            boolean succeed = f.isSuccess();

            logger.warn("Reconnects with {}, {}.", remoteAddress, succeed ? "succeed" : "failed");

            if (!succeed) {
                f.channel().pipeline().fireChannelInactive();
            }
        }
    });
}

From source file:org.jupiter.transport.netty.JNettyConnection.java

License:Apache License

@Override
public void operationComplete(final Runnable callback) {
    future.addListener(new ChannelFutureListener() {

        @Override//  w ww  .  ja v  a2 s .c o m
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                callback.run();
            }
        }
    });
}

From source file:org.kobeyoung81.dummyhttpproxy.HexDumpProxyBackendHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {

    inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
        @Override//  ww  w.  jav  a 2 s  .  c  o  m
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                ctx.channel().read();
            } else {
                future.channel().close();
            }
        }
    });
}

From source file:org.kobeyoung81.dummyhttpproxy.HexDumpProxyFrontendHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass())
            .handler(new HexDumpProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false);

    ChannelFuture f = b.connect(remoteHost, remotePort);
    outboundChannel = f.channel();/* www . j  a  v  a 2s .c om*/

    if ("local".equals(role)) {
        outboundChannel.pipeline().addLast(new SnappyFramedEncoder());
        outboundChannel.pipeline().addLast(new DummyHttpRequestEncoder());
        outboundChannel.pipeline().addFirst(new SnappyFramedDecoder());
        outboundChannel.pipeline().addFirst(new DummyHttpResponseDecoder());
    }

    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has
                // failed.
                inboundChannel.close();
            }
        }
    });
}

From source file:org.kobeyoung81.dummyhttpproxy.HexDumpProxyFrontendHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
    if (outboundChannel.isActive()) {
        outboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
            @Override/* w w  w. jav a2 s.  c  om*/
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    // was able to flush out data, start to read the
                    // next chunk
                    ctx.channel().read();
                } else {
                    future.channel().close();
                }
            }
        });
    }
}

From source file:org.kobeyoung81.hexdumpproxy.HexDumpProxyFrontendHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass())
            .handler(new HexDumpProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false);

    ChannelFuture f = b.connect(remoteHost, remotePort);
    outboundChannel = f.channel();/*from www. ja v a2  s .  co m*/

    if ("local".equals(role)) {
        outboundChannel.pipeline().addLast(new SnappyFramedEncoder());
        outboundChannel.pipeline().addFirst(new SnappyFramedDecoder());
    }

    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has
                // failed.
                inboundChannel.close();
            }
        }
    });
}

From source file:org.kobeyoung81.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override// ww  w  .  j  a  va  2  s .  co  m
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .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));
                            }
                        });
                //System.out.println(request.toString());
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                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));
    //System.out.println(request.host() +":"+ request.port());
    //SocksCmdRequest re = new SocksCmdRequest(request.cmdType(), request.addressType(), "192.168.87.103", 8080);
    b.connect(request.host(), request.port()).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 SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

From source file:org.kurento.jsonrpc.client.JsonRpcClientNettyWebSocket.java

License:Apache License

@Override
protected void connectNativeClient() throws TimeoutException, Exception {

    if (channel == null || !channel.isActive() || group == null || group.isShuttingDown()
            || group.isShutdown()) {/* w w w .  jav  a2s .co m*/

        log.info("{} Connecting native client", label);

        final boolean ssl = "wss".equalsIgnoreCase(this.uri.getScheme());
        final SslContext sslCtx;
        try {
            sslCtx = ssl
                    ? SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build()
                    : null;
        } catch (SSLException e) {
            log.error("{} Could not create SSL Context", label, e);
            throw new IllegalArgumentException("Could not create SSL context. See logs for more details", e);
        }

        final String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
        final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
        final int port;
        if (uri.getPort() == -1) {
            if ("ws".equalsIgnoreCase(scheme)) {
                port = 80;
            } else if ("wss".equalsIgnoreCase(scheme)) {
                port = 443;
            } else {
                port = -1;
            }
        } else {
            port = uri.getPort();
        }

        if (group == null || group.isShuttingDown() || group.isShutdown() || group.isTerminated()) {
            log.info("{} Creating new NioEventLoopGroup", label);
            group = new NioEventLoopGroup();
        }

        if (channel != null) {
            log.info("{} Closing previously existing channel when connecting native client", label);
            closeChannel();
        }

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                log.info("{} Inititating new Netty channel. Will create new handler too!", label);
                handler = new JsonRpcWebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri,
                        WebSocketVersion.V13, null, true, new DefaultHttpHeaders(), maxPacketSize));

                ChannelPipeline p = ch.pipeline();
                p.addLast("idleStateHandler", new IdleStateHandler(0, 0, idleTimeout / 1000));
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192),
                        WebSocketClientCompressionHandler.INSTANCE, handler);
            }
        }).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, this.connectionTimeout);

        int numRetries = 0;
        final int maxRetries = 5;
        while (channel == null || !channel.isOpen()) {
            try {
                channel = b.connect(host, port).sync().channel();
                handler.handshakeFuture().sync();
            } catch (InterruptedException e) {
                // This should never happen
                log.warn("{} ERROR connecting WS Netty client, opening channel", label, e);
            } catch (Exception e) {
                if (e.getCause() instanceof WebSocketHandshakeException && numRetries < maxRetries) {
                    log.warn(
                            "{} Upgrade exception when trying to connect to {}. Try {} of {}. Retrying in 200ms ",
                            label, uri, numRetries + 1, maxRetries);
                    Thread.sleep(200);
                    numRetries++;
                } else {
                    throw e;
                }
            }

        }

        channel.closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.info("{} channel closed", label);
                handleReconnectDisconnection(1001, "Channel closed");
            }
        });

    }

}

From source file:org.lightmare.remote.rpc.RpcHandler.java

License:Open Source License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws IOException {

    RpcWrapper wrapper = ObjectUtils.cast(msg, RpcWrapper.class);

    RcpWrapper rcp = new RcpWrapper();
    Object value;//from   w  ww  .  ja  v  a  2  s  . co m
    try {
        value = RpcUtils.callBeanMethod(wrapper);
        rcp.setValid(Boolean.TRUE);
    } catch (Exception ex) {
        LOG.error(ex.getMessage(), ex);
        value = ex;
    }

    rcp.setValue(value);

    final ChannelFuture future = ctx.writeAndFlush(rcp);

    future.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture lisFuture) {

            try {
                assert (future == lisFuture);
            } finally {
                ctx.close();
            }
        }
    });
}