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:cc.io.lessons.server.HttpUploadServerHandler.java

License:Apache License

private void writeResponse(Channel channel) {
    // Convert the response content to a ChannelBuffer.
    ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    responseContent.setLength(0);/*from  www  .j  ava2 s  . c om*/

    // Decide whether to close the connection or not.
    boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.headers().get(CONNECTION))
            || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0)
                    && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request.headers().get(CONNECTION));

    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (!close) {
        // There's no need to add 'Content-Length' header
        // if this is the last response.
        response.headers().set(CONTENT_LENGTH, buf.readableBytes());
    }

    Set<Cookie> cookies;
    String value = request.headers().get(COOKIE);
    if (value == null) {
        cookies = Collections.emptySet();
    } else {
        cookies = CookieDecoder.decode(value);
    }
    if (!cookies.isEmpty()) {
        // Reset the cookies if necessary.
        for (Cookie cookie : cookies) {
            response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie));
        }
    }
    // Write the response.
    ChannelFuture future = channel.writeAndFlush(response);
    // Close the connection after the write operation is done if necessary.
    if (close) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:chapter10.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // /* w  w w  . j  a  v  a  2 s . c o m*/
    if (res.status().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        setContentLength(res, res.content().readableBytes());
    }

    // ?Keep-Alive
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!isKeepAlive(req) || res.status().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

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;//w  ww .ja va  2 s  .  com
    }

    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 {/* w ww.j  ava2 s  .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.BasePageDispatcher.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (AssertUtil.isNotNull(msg)) {
        ContextAttachment attach = getAttach(ctx);
        try {// w  w  w  . ja  va  2 s  .c  om
            if (msg instanceof HttpMessage) {
                HttpRequest request = null;
                if (msg instanceof AggregatedFullHttpMessage) {
                    AggregatedFullHttpMessage aggregatedFullHttpMessage = (AggregatedFullHttpMessage) msg;
                    request = (HttpRequest) aggregatedFullHttpMessage.message;
                } else {
                    request = (HttpRequest) msg;
                }
                request.setRemoteAddress(ctx.channel().remoteAddress());
                request.setLocalAddress(ctx.channel().localAddress());
                attach.registerNewMessage(request);
                requestReceived(ctx, attach);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ChannelFuture future = ctx.writeAndFlush(attach.getResponse().copy());
            attach.markWriteEnd();
            //
            config.countStat.responseSended(ctx, attach);
            //
            config.timeSpanStat.writeEnd(attach);
            future.addListener(attach);
        }
    }
}

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;// w w  w. j av  a  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:cn.yesway.demo.book.protocol.http.fileServer.HttpFileServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);/*from  w  ww  .j ava 2s.c  o  m*/
        return;
    }
    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }
    final String uri = request.getUri();
    final String path = sanitizeUri(uri);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    if (file.isDirectory()) {
        if (uri.endsWith("/")) {
            sendListing(ctx, file);
        } else {
            sendRedirect(ctx, uri + '/');
        }
        return;
    }
    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    RandomAccessFile randomAccessFile = null;
    try {
        randomAccessFile = new RandomAccessFile(file, "r");// ??
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = randomAccessFile.length();
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    if (isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }
    ctx.write(response);
    ChannelFuture sendFileFuture;
    sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0, fileLength, 8192),
            ctx.newProgressivePromise());
    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println("Transfer progress: " + progress);
            } else {
                System.err.println("Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) throws Exception {
            System.out.println("Transfer complete.");
        }
    });
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    if (!isKeepAlive(request)) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:cn.yesway.demo.book.protocol.http.xml.server.HttpXmlServerHandler.java

License:Apache License

@Override
public void messageReceived(final ChannelHandlerContext ctx, HttpXmlRequest xmlRequest) throws Exception {
    HttpRequest request = xmlRequest.getRequest();
    Order order = (Order) xmlRequest.getBody();
    System.out.println("Http server receive request : " + order);
    dobusiness(order);/* w ww  . ja v  a2s . c o m*/
    ChannelFuture future = ctx.writeAndFlush(new HttpXmlResponse(null, order));
    if (!isKeepAlive(request)) {
        future.addListener(new GenericFutureListener<Future<? super Void>>() {
            public void operationComplete(Future future) throws Exception {
                ctx.close();
            }
        });
    }
}

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  .  ja  v  a2s.  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  ww w  . ja v a  2  s  .c  o 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());
            }
        }
    });
}