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:books.netty.protocol.http.fileServer.HttpFileServerHandler.java

License:Apache License

private static void sendRedirect(ChannelHandlerContext ctx, String newUri) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
    response.headers().set(LOCATION, newUri);
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:books.netty.protocol.http.fileServer.HttpFileServerHandler.java

License:Apache License

private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status,
            Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:books.netty.protocol.http.xml.server.HttpXmlServerHandler.java

License:Apache License

private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status,
            Unpooled.copiedBuffer(": " + status.toString() + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:books.netty.protocol.websocket.server.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // /*  w  w w  .ja va 2s. c o m*/
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().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.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:bzh.ygu.fun.chitchat.HttpChitChatServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);/*from w  w  w  .  j a  v a 2  s.  c o  m*/
        }
        String uri = request.uri();
        HttpMethod method = request.method();
        Root root = Root.getInstance();
        buf.setLength(0);
        contentBuf.setLength(0);

        if (method == HttpMethod.POST) {
            if (uri.equals("/chitchat")) {

                currentAction = "Add";
            }
        }
        if (method == HttpMethod.GET) {
            if (uri.startsWith(LATEST)) {
                latestFromWho = decode(uri.substring(LATEST_SIZE));
                currentAction = "Latest";
                Message m = root.getLatest(latestFromWho);
                if (m != null) {
                    //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715}
                    buf.append(m.toJSON());
                }
            }
            if (uri.startsWith(THREADCALL)) {
                currentAction = "Thread";
                String threadId = uri.substring(THREADCALL_SIZE);
                MessageThread mt = root.getMessageThread(threadId);
                if (mt != null) {
                    //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715}
                    buf.append(mt.toJSON());
                }

            }
            if (uri.startsWith(SEARCH)) {
                String stringToSearch = decode(uri.substring(SEARCH_SIZE));
                currentAction = "search";
                List<Message> lm = root.search(stringToSearch);
                //[{"author":"Loki", "text":"I have an army !", "thread":3,
                //"createdAt":1404736639710}, {"author":"Iron Man", "text":"We have a Hulk !",
                //   "thread":3, "createdAt":1404736639715}]
                buf.append("[");
                if (!lm.isEmpty()) {
                    Iterator<Message> it = lm.iterator();
                    Message m = it.next();
                    buf.append(m.toJSON());
                    while (it.hasNext()) {
                        m = it.next();
                        buf.append(", ");
                        buf.append(m.toJSON());
                    }
                }

                buf.append("]");
            }
        }
    }

    if (msg instanceof HttpContent) {
        Root root = Root.getInstance();
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            contentBuf.append(content.toString(CharsetUtil.UTF_8));
        }

        if (msg instanceof LastHttpContent) {
            //                buf.append("END OF CONTENT\r\n");
            if (currentAction.equals("Add")) {
                addMessageFromContent(contentBuf.toString(), root);
                currentAction = "None";
            }
            LastHttpContent trailer = (LastHttpContent) msg;

            if (!writeResponse(trailer, ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
}

From source file:ca.lambtoncollege.netty.webSocket.ServerHandlerWebSocket.java

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/* www.  j a  v  a 2s  . com*/
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:cc.agentx.client.net.nio.Socks5Handler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, SocksRequest request) throws Exception {
    switch (request.protocolVersion()) {
    case SOCKS4a:
        log.warn("\tBad Handshake! (protocol version not supported: 4)");
        ctx.write(new SocksInitResponse(SocksAuthScheme.UNKNOWN));
        if (ctx.channel().isActive()) {
            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }/*  ww  w . j  a  v a 2  s  .  c  om*/
        break;
    case SOCKS5:
        switch (request.requestType()) {
        case INIT:
            ctx.pipeline().addFirst(new SocksCmdRequestDecoder());
            ctx.write(new SocksInitResponse(SocksAuthScheme.NO_AUTH));
            break;
        case AUTH:
            ctx.pipeline().addFirst(new SocksCmdRequestDecoder());
            ctx.write(new SocksAuthResponse(SocksAuthStatus.SUCCESS));
            break;
        case CMD:
            if (((SocksCmdRequest) request).cmdType() == SocksCmdType.CONNECT) {
                ctx.pipeline().addLast(new XConnectHandler());
                ctx.pipeline().remove(this);
                ctx.fireChannelRead(request);
            } else {
                ctx.close();
                log.warn("\tBad Handshake! (command not support: {})", ((SocksCmdRequest) request).cmdType());
            }
            break;
        case UNKNOWN:
            log.warn("\tBad Handshake! (unknown request type)");
        }
        break;
    case UNKNOWN:
        log.warn("\tBad Handshake! (protocol version not support: {}", request.protocolVersion());
        ctx.close();
        break;
    }
}

From source file:cc.agentx.client.net.nio.Socks5Handler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
    throwable.printStackTrace();//ww  w . j  a v a2  s.c om
    if (ctx.channel().isActive()) {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:cc.agentx.client.net.nio.XConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    boolean proxyMode = isAgentXNeeded(request.host());
    log.info("\tClient -> Proxy           \tTarget {}:{} [{}]", request.host(), request.port(),
            proxyMode ? "AGENTX" : "DIRECT");
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new FutureListener<Channel>() {
        @Override//from w w  w  . ja  v  a  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(channelFuture -> {
                            ByteBuf byteBuf = Unpooled.buffer();
                            request.encodeAsByteBuf(byteBuf);
                            if (byteBuf.hasArray()) {
                                byte[] xRequestBytes = new byte[byteBuf.readableBytes()];
                                byteBuf.getBytes(0, xRequestBytes);

                                if (proxyMode) {
                                    // handshaking to remote proxy
                                    xRequestBytes = requestWrapper.wrap(xRequestBytes);
                                    outboundChannel.writeAndFlush(Unpooled.wrappedBuffer(
                                            exposeRequest ? xRequestBytes : wrapper.wrap(xRequestBytes)));
                                }

                                // task handover
                                ReferenceCountUtil.retain(request); // auto-release? a trap?
                                ctx.pipeline().remove(XConnectHandler.this);
                                outboundChannel.pipeline().addLast(new XRelayHandler(ctx.channel(),
                                        proxyMode ? wrapper : rawWrapper, false));
                                ctx.pipeline().addLast(new XRelayHandler(outboundChannel,
                                        proxyMode ? wrapper : rawWrapper, true));
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));

                if (ctx.channel().isActive()) {
                    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                }
            }
        }
    });

    String host = request.host();
    int port = request.port();
    if (host.equals(config.getConsoleDomain())) {
        host = "localhost";
        port = config.getConsolePort();
    } else if (proxyMode) {
        host = config.getServerHost();
        port = config.getServerPort();
    }

    // ping target
    bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port)
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.channel().writeAndFlush(
                                new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                        if (ctx.channel().isActive()) {
                            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        }
                    }
                }
            });
}

From source file:cc.agentx.client.net.nio.XConnectHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    if (ctx.channel().isActive()) {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }/*from   w ww. j a  va 2  s  . c  om*/
    log.warn("\tBad Connection! ({})", cause.getMessage());
}