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:club.lovety.xy.netty.test.UptimeClient.java

License:Apache License

static void connect(Bootstrap b) {
    b.connect().addListener(new ChannelFutureListener() {
        @Override// w w  w.  j a  v a  2 s .  c o  m
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.cause() != null) {
                handler.startTime = -1;
                handler.println("Failed to connect: " + future.cause());
            }
        }
    });
}

From source file:cn.david.socks.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/* w  w  w. j a v  a2s . c om*/
        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));
                            }
                        });
            } 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));

    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:cn.savor.small.netty.NettyClient.java

License:Open Source License

public void connect() {
    System.out.println("client connection.................");
    if (channel != null && channel.isActive()) {
        return;/* ww  w  . ja  va  2 s  . c  om*/
    }

    ChannelFuture future = bootstrap.connect(host, port);
    System.out.println("client connection.................host=" + host + ",port=" + port + ",future="
            + future.isSuccess());

    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture futureListener) throws Exception {
            if (futureListener.isSuccess()) {
                channel = futureListener.channel();
                System.out.println("Connect to server successfully!");
            } else {
                System.out.println("Failed to connect to server, try connect after 10s");

                futureListener.channel().eventLoop().schedule(new Runnable() {
                    @Override
                    public void run() {
                        connect();
                    }
                }, 1, TimeUnit.SECONDS);
            }
        }
    });
}

From source file:cn.scujcc.bug.bitcoinplatformandroid.util.socket.websocket.WebSocketBase.java

License:Apache License

private void connect() {
    try {//from  w w w .  j a  va2s.c o m
        final URI uri = new URI(url);
        if (uri == null) {
            return;
        }
        if (uri.getHost().contains("com")) {
            siteFlag = 1;
        }
        group = new NioEventLoopGroup(1);
        bootstrap = new Bootstrap();
        final SslContext sslCtx = SslContext.newClientContext();
        final WebSocketClientHandler handler = new WebSocketClientHandler(
                WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false,
                        new DefaultHttpHeaders(), Integer.MAX_VALUE),
                service, moniter);
        bootstrap.group(group).option(ChannelOption.TCP_NODELAY, true).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc(), uri.getHost(), uri.getPort()));
                        }
                        p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
                    }
                });

        future = bootstrap.connect(uri.getHost(), uri.getPort());
        future.addListener(new ChannelFutureListener() {
            public void operationComplete(final ChannelFuture future) throws Exception {
            }
        });
        channel = future.sync().channel();
        handler.handshakeFuture().sync();
        this.setStatus(true);
    } catch (Exception e) {
        Log.e(TAG, "WebSocketClient start error " + e.getLocalizedMessage());
        group.shutdownGracefully();
        this.setStatus(false);
    }
}

From source file:cn.wantedonline.puppy.httpserver.component.HttpObjectAggregator.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception {
    AggregatedFullHttpMessage currentMessage = this.currentMessage;

    if (msg instanceof HttpMessage) {
        tooLongFrameFound = false;/* ww w.j  a  va 2s .co  m*/
        assert currentMessage == null;

        HttpMessage m = (HttpMessage) msg;

        // Handle the 'Expect: 100-continue' header if necessary.
        if (is100ContinueExpected(m)) {
            if (HttpHeaders.getContentLength(m, 0) > maxContentLength) {
                tooLongFrameFound = true;
                final ChannelFuture future = ctx.writeAndFlush(EXPECTATION_FAILED.duplicate().retain());
                future.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (!future.isSuccess()) {
                            ctx.fireExceptionCaught(future.cause());
                        }
                    }
                });
                if (closeOnExpectationFailed) {
                    future.addListener(ChannelFutureListener.CLOSE);
                }
                ctx.pipeline().fireUserEventTriggered(HttpExpectationFailedEvent.INSTANCE);
                return;
            }
            ctx.writeAndFlush(CONTINUE.duplicate().retain()).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.fireExceptionCaught(future.cause());
                    }
                }
            });
        }

        if (!m.getDecoderResult().isSuccess()) {
            removeTransferEncodingChunked(m);
            out.add(toFullMessage(m));
            this.currentMessage = null;
            return;
        }
        if (msg instanceof HttpRequest) {
            HttpRequest header = (HttpRequest) msg;
            this.currentMessage = currentMessage = new AggregatedFullHttpRequest(header,
                    ctx.alloc().compositeBuffer(maxCumulationBufferComponents), null);
        } else if (msg instanceof HttpResponse) {
            HttpResponse header = (HttpResponse) msg;
            this.currentMessage = currentMessage = new AggregatedFullHttpResponse(header,
                    Unpooled.compositeBuffer(maxCumulationBufferComponents), null);
        } else {
            throw new Error();
        }

        // A streamed message - initialize the cumulative buffer, and wait for incoming chunks.
        removeTransferEncodingChunked(currentMessage);
    } else if (msg instanceof HttpContent) {
        if (tooLongFrameFound) {
            if (msg instanceof LastHttpContent) {
                this.currentMessage = null;
            }
            // already detect the too long frame so just discard the content
            return;
        }
        assert currentMessage != null;

        // Merge the received chunk into the content of the current message.
        HttpContent chunk = (HttpContent) msg;
        CompositeByteBuf content = (CompositeByteBuf) currentMessage.content();

        if (content.readableBytes() > maxContentLength - chunk.content().readableBytes()) {
            tooLongFrameFound = true;

            // release current message to prevent leaks
            currentMessage.release();
            this.currentMessage = null;

            throw new TooLongFrameException("HTTP content length exceeded " + maxContentLength + " bytes.");
        }

        // Append the content of the chunk
        if (chunk.content().isReadable()) {
            chunk.retain();
            content.addComponent(chunk.content());
            content.writerIndex(content.writerIndex() + chunk.content().readableBytes());
        }

        final boolean last;
        if (!chunk.getDecoderResult().isSuccess()) {
            currentMessage.setDecoderResult(DecoderResult.failure(chunk.getDecoderResult().cause()));
            last = true;
        } else {
            last = chunk instanceof LastHttpContent;
        }

        if (last) {
            this.currentMessage = null;

            // Merge trailing headers into the message.
            if (chunk instanceof LastHttpContent) {
                LastHttpContent trailer = (LastHttpContent) chunk;
                currentMessage.setTrailingHeaders(trailer.trailingHeaders());
            } else {
                currentMessage.setTrailingHeaders(new DefaultHttpHeaders());
            }

            // Set the 'Content-Length' header. If one isn't already set.
            // This is important as HEAD responses will use a 'Content-Length' header which
            // does not match the actual body, but the number of bytes that would be
            // transmitted if a GET would have been used.
            //
            // See rfc2616 14.13 Content-Length
            if (!isContentLengthSet(currentMessage)) {
                currentMessage.headers().set(HttpHeaders.Names.CONTENT_LENGTH,
                        String.valueOf(content.readableBytes()));
            }
            // All done
            out.add(currentMessage);
        }
    } else {
        throw new Error();
    }
}

From source file:code.google.nfs.rpc.netty.client.NettyClient.java

License:Apache License

public void sendRequest(final RequestWrapper wrapper, final int timeout) throws Exception {
    final long beginTime = System.currentTimeMillis();
    final Client self = this;
    ChannelFuture writeFuture = cf.channel().writeAndFlush(wrapper);
    // use listener to avoid wait for write & thread context switch
    writeFuture.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                return;
            }/*from  w w w  .  jav a2  s.  c  o m*/
            String errorMsg = "";
            // write timeout
            if (System.currentTimeMillis() - beginTime >= timeout) {
                errorMsg = "write to send buffer consume too long time("
                        + (System.currentTimeMillis() - beginTime) + "),request id is:" + wrapper.getId();
            }
            if (future.isCancelled()) {
                errorMsg = "Send request to " + cf.channel().toString() + " cancelled by user,request id is:"
                        + wrapper.getId();
            }
            if (!future.isSuccess()) {
                if (cf.channel().isOpen()) {
                    // maybe some exception,so close the channel
                    cf.channel().close();
                } else {
                    NettyClientFactory.getInstance().removeClient(key, self);
                }
                errorMsg = "Send request to " + cf.channel().toString() + " error" + future.cause();
            }
            LOGGER.error(errorMsg);
            ResponseWrapper response = new ResponseWrapper(wrapper.getId(), wrapper.getCodecType(),
                    wrapper.getProtocolType());
            response.setException(new Exception(errorMsg));
            self.putResponse(response);
        }
    });
}

From source file:code.google.nfs.rpc.netty.server.NettyServerHandler.java

License:Apache License

private void sendErrorResponse(final ChannelHandlerContext ctx, final RequestWrapper request) {
    ResponseWrapper responseWrapper = new ResponseWrapper(request.getId(), request.getCodecType(),
            request.getProtocolType());/*from   w w w .  j ava  2s  . co  m*/
    responseWrapper.setException(
            new Exception("server threadpool full,maybe because server is slow or too many requests"));
    ChannelFuture wf = ctx.channel().writeAndFlush(responseWrapper);
    wf.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                LOGGER.error("server write response error,request id is: " + request.getId());
            }
        }
    });
}

From source file:code.google.nfs.rpc.netty4.client.Netty4Client.java

License:Apache License

public void sendRequest(final RequestWrapper wrapper, final int timeout) throws Exception {
    final long beginTime = System.currentTimeMillis();
    final Client self = this;
    ChannelFuture writeFuture = cf.channel().writeAndFlush(wrapper);
    // use listener to avoid wait for write & thread context switch
    writeFuture.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                return;
            }/*www  .  j  ava2 s . com*/
            String errorMsg = "";
            // write timeout
            if (System.currentTimeMillis() - beginTime >= timeout) {
                errorMsg = "write to send buffer consume too long time("
                        + (System.currentTimeMillis() - beginTime) + "),request id is:" + wrapper.getId();
            }
            if (future.isCancelled()) {
                errorMsg = "Send request to " + cf.channel().toString() + " cancelled by user,request id is:"
                        + wrapper.getId();
            }
            if (!future.isSuccess()) {
                if (cf.channel().isActive()) {
                    // maybe some exception,so close the channel
                    cf.channel().close();
                } else {
                    Netty4ClientFactory.getInstance().removeClient(key, self);
                }
                errorMsg = "Send request to " + cf.channel().toString() + " error" + future.cause();
            }
            LOGGER.error(errorMsg);
            ResponseWrapper response = new ResponseWrapper(wrapper.getId(), wrapper.getCodecType(),
                    wrapper.getProtocolType());
            response.setException(new Exception(errorMsg));
            self.putResponse(response);
        }
    });
}

From source file:code.google.nfs.rpc.netty4.server.Netty4ServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    RequestWrapper request = (RequestWrapper) msg;
    long beginTime = System.currentTimeMillis();
    ResponseWrapper responseWrapper = ProtocolFactory.getServerHandler(request.getProtocolType())
            .handleRequest(request);// w  ww .  j  a  v  a  2  s.  com
    final int id = request.getId();
    // already timeout,so not return
    if ((System.currentTimeMillis() - beginTime) >= request.getTimeout()) {
        LOGGER.warn("timeout,so give up send response to client,requestId is:" + id + ",client is:"
                + ctx.channel().remoteAddress() + ",consumetime is:" + (System.currentTimeMillis() - beginTime)
                + ",timeout is:" + request.getTimeout());
        return;
    }
    ChannelFuture wf = ctx.channel().writeAndFlush(responseWrapper);
    wf.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                LOGGER.error("server write response error,request id is: " + id);
            }
        }
    });
}

From source file:com.addthis.hydra.query.loadbalance.NextQueryTask.java

License:Apache License

@Override
public void run() {
    QueryRequest request;/*w w  w . java2 s. c om*/
    try {
        request = queryQueue.takeQuery();
    } catch (InterruptedException ignored) {
        log.info("Frame reader thread interrupted -- halting query processing");
        return;
    }
    try {
        final ChannelFuture queryFuture = HttpQueryCallHandler.handleQuery(request.querySource, request.kv,
                request.request, request.ctx, executor);
        queryFuture.addListener(this);
        queryFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (queryFuture.cancel(false)) {
                    log.warn("cancelling query due to closed output channel");
                }
            }
        });
    } catch (Exception e) {
        log.warn("Exception caught before mesh query master added to pipeline", e);
        if (request.ctx.channel().isActive()) {
            HttpUtils.sendError(request.ctx, new HttpResponseStatus(500, e.getMessage()));
        }
    }
}