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.nettybook.ch7.junit.TelnetServerHandlerNetty.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
    System.out.println(request + " channelActive ");
    // Generate and write a response.
    String response;//from w ww. j  ava2  s. c  o  m
    boolean close = false;
    if (request.isEmpty()) {
        response = "Please type something.\r\n";
    } else if ("bye".equals(request.toLowerCase())) {
        response = "Have a good day!\r\n";
        close = true;
    } else {
        response = "Did you say '" + request + "'?\r\n";
    }

    // We do not need to write a ChannelBuffer here.
    // We know the encoder inserted at TelnetPipelineFactory will do the conversion.
    ChannelFuture future = ctx.write(response);

    // Close the connection after sending 'Have a good day!'
    // if the client has sent 'bye'.
    System.out.println(response);
    if (close) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.github.nettybook.ch7.junit.TelnetServerHandlerV3.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
    ResponseGenerator generator = new ResponseGenerator(request);

    // Generate and write a response.
    String response = generator.response();

    // We do not need to write a ChannelBuffer here.
    // We know the encoder inserted at TelnetPipelineFactory will do the
    // conversion.
    ChannelFuture future = ctx.write(response);

    // Close the connection after sending 'Have a good day!'
    // if the client has sent 'bye'.
    if (generator.isClose()) {
        future.addListener(ChannelFutureListener.CLOSE);
    }//  w  ww. j a  v a2  s  .c o m
}

From source file:com.github.nettybook.ch8.TelnetServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
    // Generate and write a response.
    String response;// w  w  w. j av a2s . c  o m
    boolean close = false;
    if (request.isEmpty()) {
        response = "?  .\r\n";
    } else if ("bye".equals(request.toLowerCase())) {
        response = " !\r\n";
        close = true;
    } else {
        response = " ? '" + request + "' .\r\n";
    }

    // TelnetPipelineFactory? ? StringEncoder? ?? ?   
    // ChannelBuffer?  ?    ? ?? .   
    ChannelFuture future = ctx.write(response);

    // ??? bye ?  close  true? ? ? ?.
    if (close) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.github.sinsinpub.pero.backend.ConnectBackendHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    final Channel inboundChannel = ctx.channel();
    final Promise<Channel> outboundPromise = newOutboundPromise(ctx, request);
    final int maxProxies = AppProps.PROPS.getInteger("upstream.socks5.count", 1);
    final AtomicBoolean isFinalSuccess = new AtomicBoolean(false);
    final AtomicBoolean isRetryOccured = new AtomicBoolean(false);
    for (int i = 1; i <= maxProxies; i++) {
        final boolean isFirstOne = (i == 1);
        final boolean isFinalOne = (i == maxProxies);
        if (!isFirstOne) {
            isRetryOccured.set(true);/*from  w  w  w. ja  v a 2  s .  c  o  m*/
        }
        try {
            final ProxyHandler upstreamProxyHandler = newUpstreamProxyHandler(i);
            final Bootstrap b = newConnectionBootstrap(inboundChannel, outboundPromise, upstreamProxyHandler);
            logger.info(String.format("Connecting backend %s:%s via %s", request.host(), request.port(),
                    upstreamProxyHandler != null ? upstreamProxyHandler.proxyAddress() : "direct"));
            ChannelFuture connFuture = b.connect(request.host(), request.port());
            connFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        // Connection established use handler provided results
                        if (upstreamProxyHandler == null) {
                            logger.info("Backend connected directly");
                        } else {
                            logger.info("Backend connected via: " + upstreamProxyHandler.proxyAddress());
                        }
                    } else {
                        // Close the connection if the connection attempt has failed.
                        if (isFinalOne) {
                            logger.error("Backend connection failed: " + future.cause(), future.cause());
                            ctx.channel().writeAndFlush(
                                    new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                            NettyChannelUtils.closeOnFlush(ctx.channel());
                        } else {
                            logger.warn("Backend connection failed: {}", future.cause().toString());
                        }
                    }
                }
            });
            connFuture.await(getConnectTimeoutMillis(), TimeUnit.MILLISECONDS);
            if (connFuture.isSuccess()) {
                isFinalSuccess.set(true);
                break;
            }
        } catch (Exception e) {
            logger.error("Connecting exception {} caught:", e);
        }
    }
    if (isFinalSuccess.get() && isRetryOccured.get()) {
        logger.warn("Protected from Error-Neko: {} times", nekoKilled.incrementAndGet());
    }
}

From source file:com.google.devtools.build.remote.worker.HttpCacheServerHandler.java

License:Open Source License

private void handleGet(ChannelHandlerContext ctx, FullHttpRequest request) {
    byte[] contents = cache.get(request.uri());

    if (contents == null) {
        sendError(ctx, request, HttpResponseStatus.NOT_FOUND);
        return;/* w  w  w  .j av  a 2 s.  co  m*/
    }

    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.wrappedBuffer(contents));
    HttpUtil.setContentLength(response, contents.length);
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/octet-stream");
    ChannelFuture lastContentFuture = ctx.writeAndFlush(response);

    if (!HttpUtil.isKeepAlive(request)) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.google.devtools.build.remote.worker.HttpCacheServerHandler.java

License:Open Source License

private void handlePut(ChannelHandlerContext ctx, FullHttpRequest request) {
    if (!request.decoderResult().isSuccess()) {
        sendError(ctx, request, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        return;/*from   w w w . java  2s  .  c o  m*/
    }

    byte[] contentBytes = new byte[request.content().readableBytes()];
    request.content().readBytes(contentBytes);
    cache.putIfAbsent(request.uri(), contentBytes);

    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.NO_CONTENT);
    ChannelFuture lastContentFuture = ctx.writeAndFlush(response);

    if (!HttpUtil.isKeepAlive(request)) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.google.devtools.build.remote.worker.HttpCacheServerHandler.java

License:Open Source License

private static void sendError(ChannelHandlerContext ctx, FullHttpRequest request, HttpResponseStatus status) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
            Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
    ChannelFuture future = ctx.writeAndFlush(response);

    if (!HttpUtil.isKeepAlive(request)) {
        future.addListener(ChannelFutureListener.CLOSE);
    }//from w  w  w.  j a  v a2s.co m
}

From source file:com.google.errorprone.bugpatterns.testdata.FutureReturnValueIgnoredNegativeCases.java

License:Open Source License

void ignoreChannelFutureAddListener(ChannelFuture cf) {
    cf.addListener((ChannelFuture f) -> {
    });
}

From source file:com.googlecode.protobuf.pro.duplex.handler.ServerConnectRequestHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, WirePayload msg, List<Object> out) throws Exception {
    if (msg.hasConnectRequest()) {
        ConnectRequest connectRequest = msg.getConnectRequest();
        if (log.isDebugEnabled()) {
            log.debug("Received [" + connectRequest.getCorrelationId() + "]ConnectRequest.");
        }/* w  ww . j  a  va2 s  .  c om*/
        PeerInfo connectingClientInfo = new PeerInfo(connectRequest.getClientHostName(),
                connectRequest.getClientPort(), connectRequest.getClientPID());
        ConnectResponse connectResponse = null;

        RpcClient rpcClient = new RpcClient(ctx.channel(), pipelineFactory.getServerInfo(),
                connectingClientInfo, connectRequest.getCompress(), pipelineFactory.getLogger(),
                pipelineFactory.getExtensionRegistry());
        if (pipelineFactory.getRpcClientRegistry().registerRpcClient(rpcClient)) {
            connectResponse = ConnectResponse.newBuilder().setCorrelationId(connectRequest.getCorrelationId())
                    .setServerPID(pipelineFactory.getServerInfo().getPid())
                    .setCompress(connectRequest.getCompress()).build();
            WirePayload payload = WirePayload.newBuilder().setConnectResponse(connectResponse).build();

            if (log.isDebugEnabled()) {
                log.debug("Sending [" + connectResponse.getCorrelationId() + "]ConnectResponse.");
            }
            ctx.channel().writeAndFlush(payload);

            // now we swap this Handler out of the pipeline and complete the server side pipeline.
            RpcClientHandler clientHandler = pipelineFactory.completePipeline(rpcClient);
            clientHandler.notifyOpened();
        } else {
            connectResponse = ConnectResponse.newBuilder().setCorrelationId(connectRequest.getCorrelationId())
                    .setErrorCode(ConnectErrorCode.ALREADY_CONNECTED).build();
            WirePayload payload = WirePayload.newBuilder().setConnectResponse(connectResponse).build();

            if (log.isDebugEnabled()) {
                log.debug("Sending [" + connectResponse.getCorrelationId()
                        + "]ConnectResponse. Already Connected.");
            }
            ChannelFuture future = ctx.channel().writeAndFlush(payload);
            future.addListener(ChannelFutureListener.CLOSE); // close after write response.
        }
    } else {
        out.add(msg);
    }
}

From source file:com.gxkj.demo.netty.proxy.HexDumpProxyFrontendHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    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   ww w .j  av  a 2 s  .  c o  m*/
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });
}