Example usage for io.netty.channel ChannelHandlerContext flush

List of usage examples for io.netty.channel ChannelHandlerContext flush

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext flush.

Prototype

@Override
    ChannelHandlerContext flush();

Source Link

Usage

From source file:org.fiware.kiara.transport.http.HttpHandler.java

License:Open Source License

@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
    if (SYNC_REQUEST_RESPONSE && canSend.compareAndSet(false, true)) {
        semaphore.release();//from  www.j av  a 2 s. c o  m
    }
    ctx.flush();
}

From source file:org.fusesource.hawtdispatch.netty.example.EchoClientHandler.java

License:Apache License

@Override
public void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in) {
    ByteBuf out = ctx.nextOutboundByteBuffer();
    System.out.println("read:" + in.readableBytes());
    out.writeBytes(in);//from  w ww  .  j a v  a 2 s.co  m
    ctx.flush();
}

From source file:org.fusesource.hawtdispatch.netty.example.EchoServerHandler.java

License:Apache License

@Override
public void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in) {
    ByteBuf out = ctx.nextOutboundByteBuffer();
    out.writeBytes(in);//from   w  ww. j a v a 2  s .  c  o m
    ctx.flush();
}

From source file:org.hornetq.tests.integration.transports.netty.NettyConnectorWithHTTPUpgradeTest.java

License:Apache License

private void startWebServer(int port) throws InterruptedException {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//from  ww  w  .  j a v  a2  s  .c  o  m
                protected void initChannel(SocketChannel ch) throws Exception {
                    // create a HTTP server
                    ChannelPipeline p = ch.pipeline();
                    p.addLast("decoder", new HttpRequestDecoder());
                    p.addLast("encoder", new HttpResponseEncoder());
                    p.addLast("http-upgrade-handler", new SimpleChannelInboundHandler<Object>() {
                        // handle HTTP GET + Upgrade with a handshake specific to HornetQ remoting.
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if (msg instanceof HttpRequest) {
                                HttpRequest request = (HttpRequest) msg;

                                for (Map.Entry<String, String> entry : request.headers()) {
                                    System.out.println(entry);
                                }
                                String upgrade = request.headers().get(UPGRADE);
                                String secretKey = request.headers().get(SEC_HORNETQ_REMOTING_KEY);

                                FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
                                        SWITCHING_PROTOCOLS);
                                response.headers().set(UPGRADE, upgrade);
                                response.headers().set(SEC_HORNETQ_REMOTING_ACCEPT,
                                        createExpectedResponse(MAGIC_NUMBER, secretKey));
                                ctx.writeAndFlush(response);

                                // when the handshake is successful, the HTTP handlers are removed
                                ctx.pipeline().remove("decoder");
                                ctx.pipeline().remove("encoder");
                                ctx.pipeline().remove(this);

                                System.out.println("HTTP handshake sent, transferring channel");
                                // transfer the control of the channel to the Netty Acceptor
                                NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService()
                                        .getAcceptor(acceptorName);
                                acceptor.transfer(ctx.channel());
                                // at this point, the HTTP upgrade process is over and the netty acceptor behaves like regular ones.
                            }
                        }
                    });
                }

                @Override
                public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                    ctx.flush();
                }
            });
    b.bind(port).sync();
}

From source file:org.ireland.jnetty.http.HttpServletResponseImpl.java

License:Open Source License

/**
 * ??//from  w w  w. j av  a2  s.c om
 * 
 * @param ctx
 * @param request
 * @param response
 */
private void writeResponse(ChannelHandlerContext ctx, FullHttpRequest request, FullHttpResponse response) {
    // Set the Status Code
    response.setStatus(
            _reason == null ? HttpResponseStatus.valueOf(_status) : new HttpResponseStatus(_status, _reason));

    // set the Servlet Header :)
    response.headers().set(HttpHeaders.Names.SERVER, "JNetty");

    // Set the "Content-Length" Header
    response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

    boolean keepAlive = true;

    if (headers.get(HttpHeaders.Names.CONNECTION) != null) {
        keepAlive = HttpHeaders.isKeepAlive(response); // ?KeepAlive
    } else
    // CONNECTION?
    {
        // Decide whether to close the connection or not.
        keepAlive = HttpHeaders.isKeepAlive(request); // CONNECTION,??CONNECTION

        // TODO:think about how to decide keepAlive or not
        if (keepAlive) {
            // Add keep alive header as per:
            // http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
            response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        } else {
            response.headers().set(CONNECTION, HttpHeaders.Values.CLOSE);
        }
    }

    // Write the response.
    ctx.nextOutboundMessageBuffer().add(response);

    if (keepAlive) {
        ctx.flush();
    } else {
        //CONNECTION == "close" Close the non-keep-alive connection after the write operation is done.

        ctx.flush().addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:org.ireland.jnetty.JNettyServerHandler.java

License:Apache License

private void writeResponse(ChannelHandlerContext ctx, HttpObject currentObj) {
    // Decide whether to close the connection or not.
    boolean keepAlive = isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
            currentObj.getDecoderResult().isSuccess() ? OK : BAD_REQUEST,
            Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().set(CONTENT_LENGTH, response.data().readableBytes());
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }/*from   ww w  . ja  v a 2  s  . com*/

    // Encode the cookie.
    String cookieString = request.headers().get(COOKIE);
    if (cookieString != null) {
        Set<Cookie> cookies = CookieDecoder.decode(cookieString);
        if (!cookies.isEmpty()) {
            // Reset the cookies if necessary.
            for (Cookie cookie : cookies) {
                response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie));
            }
        }
    } else {
        // Browser sent no cookie.  Add some.
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key1", "value1"));
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key2", "value2"));
    }

    // Write the response.
    ctx.nextOutboundMessageBuffer().add(response);

    // Close the non-keep-alive connection after the write operation is done.
    if (!keepAlive) {
        ctx.flush().addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:org.ireland.jnetty.JNettyServerHandler.java

License:Apache License

@Override
public void endMessageReceived(ChannelHandlerContext ctx) throws Exception {
    ctx.flush();
}

From source file:org.jboss.arquillian.daemon.server.NettyServer.java

License:Apache License

private static void sendResponse(final ChannelHandlerContext ctx, final ByteBuf out, final String response) {
    out.discardReadBytes();//from www  .  ja v a  2s.c o m
    try {
        out.writeBytes(response.getBytes(WireProtocol.CHARSET));
        out.writeBytes(Delimiters.lineDelimiter()[0]);
    } catch (final UnsupportedEncodingException uee) {
        throw new RuntimeException("Unsupported encoding", uee);
    }
    ctx.flush();
}

From source file:org.jfxvnc.net.rfb.codec.ProtocolHandler.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {

    if (msg instanceof ImageRect) {
        render.render((ImageRect) msg, () -> {
            // logger.debug("render completed");
            // sendFramebufferUpdateRequest(ctx, true, 0, 0,
            // serverInit.getFrameBufferWidth(),
            // serverInit.getFrameBufferHeight());

        });// w  w  w  . j  ava2  s  .  c  o m
        return;
    }
    if (msg instanceof ServerDecoderEvent) {
        render.eventReceived((ServerDecoderEvent) msg);
        return;
    }

    if (!(msg instanceof ServerInitEvent)) {
        logger.error("unknown message: {}", msg);
        ctx.fireChannelRead(msg);
        return;
    }

    serverInit = (ServerInitEvent) msg;
    logger.debug("handshake completed with {}", serverInit);

    FrameDecoderHandler frameHandler = new FrameDecoderHandler(serverInit.getPixelFormat());
    if (!frameHandler.isPixelFormatSupported()) {
        ProtocolException e = new ProtocolException(String.format("pixelformat: (%s bpp) not supported yet",
                serverInit.getPixelFormat().getBitPerPixel()));
        exceptionCaught(ctx, e);
        return;
    }

    ChannelPipeline cp = ctx.pipeline();

    cp.addBefore(ctx.name(), "rfb-encoding-encoder", new PreferedEncodingEncoder());
    PreferedEncoding prefEncodings = getPreferedEncodings(frameHandler.getSupportedEncodings());
    ctx.write(prefEncodings);

    cp.addBefore(ctx.name(), "rfb-pixelformat-encoder", new PixelFormatEncoder());
    ctx.write(serverInit.getPixelFormat());
    ctx.flush();

    cp.addBefore(ctx.name(), "rfb-frame-handler", frameHandler);
    cp.addBefore(ctx.name(), "rfb-keyevent-encoder", new KeyButtonEventEncoder());
    cp.addBefore(ctx.name(), "rfb-pointerevent-encoder", new PointerEventEncoder());
    cp.addBefore(ctx.name(), "rfb-cuttext-encoder", new ClientCutTextEncoder());

    render.eventReceived(getConnectInfoEvent(ctx, prefEncodings));

    render.registerInputEventListener(event -> ctx.writeAndFlush(event, ctx.voidPromise()));

    logger.debug("request full framebuffer update");
    sendFramebufferUpdateRequest(ctx, false, 0, 0, serverInit.getFrameBufferWidth(),
            serverInit.getFrameBufferHeight());

    logger.trace("channel pipeline: {}", cp.toMap().keySet());
}

From source file:org.jooby.internal.netty.NettyHandler.java

License:Apache License

@Override
public void channelReadComplete(final ChannelHandlerContext ctx) throws Exception {
    Attribute<Boolean> attr = ctx.channel().attr(NettyRequest.NEED_FLUSH);
    boolean needFlush = (attr == null || attr.get() == Boolean.TRUE);
    if (needFlush) {
        ctx.flush();
    }// w  w w  .j a v  a2  s .  c  om
}