Example usage for io.netty.channel ChannelFutureListener CLOSE

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

Introduction

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

Prototype

ChannelFutureListener CLOSE

To view the source code for io.netty.channel ChannelFutureListener CLOSE.

Click Source Link

Document

A ChannelFutureListener that closes the Channel which is associated with the specified ChannelFuture .

Usage

From source file:com.corundumstudio.socketio.transport.FlashPolicyHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof ByteBuf) {
        ByteBuf message = (ByteBuf) msg;
        ByteBuf data = message.slice(0, requestBuffer.readableBytes());
        if (data.equals(requestBuffer)) {
            message.release();//from   w  ww .  j av  a 2s.  c  o m
            ChannelFuture f = ctx.writeAndFlush(Unpooled.copiedBuffer(responseBuffer));
            f.addListener(ChannelFutureListener.CLOSE);
            return;
        }
        ctx.pipeline().remove(this);
    }
    ctx.fireChannelRead(msg);
}

From source file:com.corundumstudio.socketio.transport.FlashUrlLoaderPolicyHandler.java

License:Apache License

/**
 * Method to write back crossdomain xml//from www .ja v  a  2 s.  co  m
 *
 * @param request
 */
private void writeCrossdomainDotXml(final ChannelHandlerContext ctx, final HttpRequest request) {
    boolean keepAlive = isKeepAlive(request);

    HttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.copiedBuffer(crossdomain));
    response.headers().set(CONTENT_TYPE, "text/xml");
    response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
    if (keepAlive) {
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        response.headers().set(HttpHeaders.Values.KEEP_ALIVE, "timeout=2,max=5");
    }
    // Write the response.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.corundumstudio.socketio.transport.PollingTransport.java

License:Apache License

private void sendError(ChannelHandlerContext ctx) {
    HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
    ctx.channel().writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.creamsugardonut.HttpStaticFileServerHandler2.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);//from ww w . j a  va  2  s  . c  o m
        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.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentTypeHeader(response, file);
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the content.
    ChannelFuture sendFileFuture;
    ChannelFuture lastContentFuture;

    // Tell clients that Partial Requests are available.
    response.headers().add(HttpHeaders.Names.ACCEPT_RANGES, HttpHeaders.Values.BYTES);

    String rangeHeader = request.headers().get(HttpHeaders.Names.RANGE);
    System.out.println(HttpHeaders.Names.RANGE + " = " + rangeHeader);
    if (rangeHeader != null && rangeHeader.length() > 0) { // Partial Request
        PartialRequestInfo partialRequestInfo = getPartialRequestInfo(rangeHeader, fileLength);

        // Set Response Header
        response.headers().add(HttpHeaders.Names.CONTENT_RANGE, HttpHeaders.Values.BYTES + " "
                + partialRequestInfo.startOffset + "-" + partialRequestInfo.endOffset + "/" + fileLength);
        System.out.println(HttpHeaders.Names.CONTENT_RANGE + " : "
                + response.headers().get(HttpHeaders.Names.CONTENT_RANGE));

        HttpHeaders.setContentLength(response, partialRequestInfo.getChunkSize());
        System.out.println(HttpHeaders.Names.CONTENT_LENGTH + " : " + partialRequestInfo.getChunkSize());

        response.setStatus(HttpResponseStatus.PARTIAL_CONTENT);

        // Write Response
        ctx.write(response);
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), partialRequestInfo.getStartOffset(),
                partialRequestInfo.getChunkSize()), ctx.newProgressivePromise());
    } else {
        // Set Response Header
        HttpHeaders.setContentLength(response, fileLength);

        // Write Response
        ctx.write(response);
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
    }

    lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println(future.channel() + " Transfer progress: " + progress);
            } else {
                System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            System.err.println(future.channel() + " Transfer complete.");
        }
    });

    // Decide whether to close the connection or not.
    if (!HttpHeaders.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.dempe.ketty.srv.http.HttpStaticFileServerHandler.java

License:Apache License

public static void sendRedirect(ChannelHandlerContext ctx, String newUri) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
    response.headers().set(LOCATION, newUri);

    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.dempe.ketty.srv.http.HttpStaticFileServerHandler.java

License:Apache License

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

    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.dempe.ketty.srv.http.HttpStaticFileServerHandler.java

License:Apache License

/**
 * When file timestamp is the same as what the browser is sending up, send a "304 Not Modified"
 *
 * @param ctx Context/*from  w  ww.  j a v  a2  s .  co  m*/
 */
public static void sendNotModified(ChannelHandlerContext ctx) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED);
    setDateHeader(response);

    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.dingwang.netty.handler.DiscardServerHandler.java

License:Open Source License

@Override
//channelActive()??
//32??/*  ww  w.j a v  a2s  .  c om*/
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    //????????32?
    //?4ByteBufChannelHandlerContext.alloc()?ByteBufAllocator
    //??
    //        final ByteBuf time = ctx.alloc().buffer(4);
    //        time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L));

    //???ChannelHandlerContext.write()(
    //writeAndFlush())ChannelFutureChannelFuture?I/O?
    //????Netty????
    //?????
    //?write()ChannelFuture??close()????
    //??,close()??ChannelFuture
    //        final ChannelFuture f = ctx.writeAndFlush(time);

    //?????ChannelFuture
    //ChannelFutureListener??ChannelFutureListener???
    //Channel????:
    //f.addListener(ChannelFutureListener.CLOSE);
    //        f.addListener(new ChannelFutureListener() {
    //            @Override
    //
    //            public void operationComplete(ChannelFuture future) {
    //                assert f == future;
    //                ctx.close();
    //
    //            }
    //        });
    System.out.println("test idle");
    ChannelFuture f = ctx.writeAndFlush("hhhh");
    f.addListener(ChannelFutureListener.CLOSE);

}

From source file:com.dingwang.rpc.handler.ProviderProxy.java

License:Open Source License

@Override
protected void messageReceived(ChannelHandlerContext ctx, RpcRequest request) throws Exception {
    System.out.println("-----------------------------------------server messageReceived");
    RpcResponse response = new RpcResponse();
    response.setRequestId(request.getRequestId());
    try {//  w ww  . j  a va2  s.  com
        Object result = handle(request);
        response.setResult(result);
    } catch (Throwable t) {
        response.setError(t);
    }
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);

}

From source file:com.dingwang.rpc.handler.RpcHandler.java

License:Open Source License

@Override
protected void messageReceived(ChannelHandlerContext ctx, RpcRequest request) throws Exception {

    System.out.println("-----------------------------------------server messageReceived");
    RpcResponse response = new RpcResponse();
    response.setRequestId(request.getRequestId());
    try {//  w  w  w .j  av a 2  s  . c  om
        Object result = handle(request);
        response.setResult(result);
    } catch (Throwable t) {
        response.setError(t);
    }
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);

}