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:reactor.ipc.netty.channel.NettyOperations.java

License:Open Source License

/**
 * Callback when a writer {@link Subscriber} has effectively terminated listening
 * on further {@link Publisher} signals.
 *
 * @param ctx the actual {@link ChannelHandlerContext}
 * @param last an optional callback for the last written payload
 * @param promise the promise to fulfil for acknowledging termination success
 * @param exception non null if the writer has terminated with a failure
 *///from w  w  w .  ja  v  a 2  s.  c  o  m
protected void doOnTerminatedWriter(ChannelHandlerContext ctx, ChannelFuture last, final ChannelPromise promise,
        final Throwable exception) {
    if (ctx.channel().isOpen()) {
        ChannelFutureListener listener = future -> {
            if (exception != null) {
                promise.tryFailure(exception);
            } else if (future.isSuccess()) {
                promise.trySuccess();
            } else {
                promise.tryFailure(future.cause());
            }
        };

        if (last != null) {
            last.addListener(listener);
            ctx.flush();
        }
    } else {
        if (exception != null) {
            promise.tryFailure(exception);
        } else {
            promise.trySuccess();
        }
    }
}

From source file:rxweb.engine.server.netty.NettyServer.java

License:Apache License

private void init() {
    this.bootstrap.option(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).group(new NioEventLoopGroup())
            .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {
                @Override//from  w  w  w .  ja va  2 s .  c  o m
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(new LoggingHandler()).addLast(new HttpServerCodec())
                            .addLast(new NettyServerCodecHandlerAdapter())
                            .addLast(new ChannelInboundHandlerAdapter() {

                                private CompletableFuture<Channel> headersSent;

                                private final Logger logger = LoggerFactory.getLogger(getClass());

                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg)
                                        throws Exception {
                                    if (msg instanceof ServerRequest) {
                                        handleRequest(ctx, (ServerRequest) msg);
                                    } else {
                                        super.channelRead(ctx, msg);
                                    }
                                }

                                private void handleRequest(ChannelHandlerContext ctx, ServerRequest request) {
                                    List<ServerHandler> handlers = handlerResolver.resolve(request);
                                    if (handlers.isEmpty()) {
                                        this.logger.info("No handler found for request " + request.getUri());
                                    }
                                    // In order to keep simple, we take the first handler
                                    ServerHandler handler = handlers.get(0);
                                    ServerResponse response = new NettyServerResponseAdapter(request);
                                    handler.handle(request, response);

                                    response.getContent().subscribe(new Subscriber<ByteBuffer>() {

                                        @Override
                                        public void onNext(ByteBuffer buffer) {
                                            if (headersSent != null) {
                                                ctx.writeAndFlush(buffer);
                                            } else {
                                                headersSent = CompletableFutureUtils
                                                        .fromChannelFuture(ctx.write(response));

                                                headersSent.handle((channel, t) -> {
                                                    if (channel != null) {
                                                        response.setStatusAndHeadersSent(true);
                                                        ctx.write(buffer);
                                                    } else {
                                                        logger.error(t.toString());
                                                    }
                                                    return channel;
                                                });
                                            }
                                        }

                                        @Override
                                        public void onError(Throwable e) {
                                            logger.error("Error in response content observable: " + e);
                                        }

                                        @Override
                                        public void onCompleted() {
                                            if (response.isStatusAndHeadersSent()) {
                                                ctx.write(new DefaultLastHttpContent());
                                                ctx.flush();
                                                ctx.close();
                                            } else if (headersSent != null) {
                                                headersSent.thenRun(() -> {
                                                    ctx.write(new DefaultLastHttpContent());
                                                    ctx.flush();
                                                    ctx.close();
                                                });
                                            } else {
                                                CompletableFutureUtils.fromChannelFuture(ctx.write(response))
                                                        .thenRun(() -> {
                                                            response.setStatusAndHeadersSent(true);
                                                            ctx.write(new DefaultLastHttpContent());
                                                            ctx.flush();
                                                            ctx.close();
                                                        });
                                            }
                                        }

                                    });
                                }

                            });
                }

            });
}

From source file:sas.systems.imflux.network.ControlPacketEncoder.java

License:Apache License

/**
 * Encodes a {@link ControlPacket} or a {@link CompoundControlPacket} to a {@link ByteBuf} and than
 * calls {@link ChannelHandlerContext#write(Object)} to forward
 * to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}.
 *//*from   w w w  .j a  v a2  s  .c  o m*/
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {

    try {
        if (msg instanceof ControlPacket) {
            ctx.write(((ControlPacket) msg).encode(), promise);
        } else if (msg instanceof CompoundControlPacket) {
            List<ControlPacket> packets = ((CompoundControlPacket) msg).getControlPackets();
            ByteBuf[] buffers = new ByteBuf[packets.size()];
            for (int i = 0; i < buffers.length; i++) {
                buffers[i] = packets.get(i).encode();
            }
            ByteBuf compoundBuffer = Unpooled.wrappedBuffer(buffers);
            ctx.write(compoundBuffer, promise);
        }
        ctx.flush();
    } catch (Exception e) {
        LOG.error("Failed to encode compound RTCP packet to send.", e);
    }
}

From source file:server.telnet.TelnetServerHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    ChannelManager.telnetMap.put(ctx.channel().id().toString(), ctx.channel());

    System.out.println("Client " + ctx.channel().remoteAddress() + " connected");
    // Send greeting for a new connection.
    ctx.write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");
    ctx.write("It is " + new Date() + " now.\r\n");
    ctx.flush();
}

From source file:sg.atom.managex.api.net.telnet.TelnetServerHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    users.put(ctx.name(), new TelnetUser(ctx.name(), new DateTime()));
    // Send greeting for a new connection.
    ctx.write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");

    ctx.write("It is " + new Date() + " now.\r\n");
    ctx.write("There are " + users.values().size() + " here!\r\n");
    for (TelnetUser user : users.values()) {
        ctx.write(user.name + " .\r\n");
    }/*ww  w .j  a va2  s.  c  om*/
    ctx.flush();
}

From source file:sn.iso4.iso8583.listener.EchoHandler.java

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
        IdleStateEvent e = (IdleStateEvent) evt;
        if (e.state() == IdleState.READER_IDLE || e.state() == IdleState.ALL_IDLE) {
            final IsoMessage echoMessage = createEchoMessage();
            ctx.write(echoMessage);//www .j  a  v a 2s .  c  o m
            ctx.flush();
        }
    }
}

From source file:spark.network.netty.FileServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, String blockId) {
    String path = pResolver.getAbsolutePath(blockId);
    // if getFilePath returns null, close the channel
    if (path == null) {
        //ctx.close();
        return;//from   www .  ja  va2s.c om
    }
    File file = new File(path);
    if (file.exists()) {
        if (!file.isFile()) {
            //logger.info("Not a file : " + file.getAbsolutePath());
            ctx.write(new FileHeader(0, blockId).buffer());
            ctx.flush();
            return;
        }
        long length = file.length();
        if (length > Integer.MAX_VALUE || length <= 0) {
            //logger.info("too large file : " + file.getAbsolutePath() + " of size "+ length);
            ctx.write(new FileHeader(0, blockId).buffer());
            ctx.flush();
            return;
        }
        int len = new Long(length).intValue();
        //logger.info("Sending block "+blockId+" filelen = "+len);
        //logger.info("header = "+ (new FileHeader(len, blockId)).buffer());
        ctx.write((new FileHeader(len, blockId)).buffer());
        try {
            ctx.sendFile(new DefaultFileRegion(new FileInputStream(file).getChannel(), 0, file.length()));
        } catch (Exception e) {
            //logger.warning("Exception when sending file : " + file.getAbsolutePath());
            e.printStackTrace();
        }
    } else {
        //logger.warning("File not found: " + file.getAbsolutePath());
        ctx.write(new FileHeader(0, blockId).buffer());
    }
    ctx.flush();
}

From source file:test.file.FileServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
    RandomAccessFile raf = null;//from   w w  w  . j  a v  a  2s  .c om
    long length = -1;
    try {
        raf = new RandomAccessFile(msg, "r");
        length = raf.length();
    } catch (Exception e) {
        ctx.writeAndFlush("ERR: " + e.getClass().getSimpleName() + ": " + e.getMessage() + '\n');
        return;
    } finally {
        if (length < 0 && raf != null) {
            raf.close();
        }
    }
    //        ctx.write("OK: " + raf.length() + '\n');
    //        if (ctx.pipeline().get(SslHandler.class) == null) {
    //            // SSL not enabled - can use zero-copy file transfer.
    //            ctx.write(new DefaultFileRegion(raf.getChannel(), 0, length));
    //        } else {
    //            SSL enabled - cannot use zero-copy file transfer.
    ctx.write(new ChunkedFile(raf));
    //        }
    ctx.flush();
    //        ctx.writeAndFlush("\n");
}

From source file:vn.com.onesoft.bigfox.server.io.core.channel.websocket.WebSocketServerHandler.java

@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
    ctx.flush();

}

From source file:xyz.kvantum.server.implementation.ResponseTask.java

License:Apache License

@SuppressWarnings("ALL")
private void sendResponse(final ChannelHandlerContext context) {
    final Timer.Context timer = KvantumServerHandler.TIMER_SEND_RESPONSE.time();

    ///*w  w w.  j  av  a  2  s.c  o m*/
    // Determine whether or not the response should be compressed
    //
    workerContext.determineGzipStatus();

    //
    // Get the generated body
    //
    ResponseBody body = workerContext.getBody();

    // Make sure that the generated response is valid (not null)
    Assert.notNull(body);
    Assert.notNull(body.getHeader());

    // Retrieve an Md5Handler from the handler pool
    // final Md5Handler md5Handler = SimpleServer.md5HandlerPool.getNullable();
    // Generate the md5 checksum
    // TODO: Re-enable this final String checksum = md5Handler.generateChecksum( bytes );
    // Update the headers to include the md5 checksum
    // body.getHeader().set( Header.HEADER_CONTENT_MD5, checksum );
    // body.getHeader().set( Header.HEADER_ETAG, checksum );
    // Return the md5 handler to the pool
    // SimpleServer.md5HandlerPool.add( md5Handler );

    //
    // Add a Last-Modified if it isn't already present in the response
    //
    if (!body.getHeader().get(Header.HEADER_LAST_MODIFIED).isPresent()) {
        body.getHeader().set(Header.HEADER_LAST_MODIFIED, TimeUtil.getHTTPTimeStamp());
    }

    //
    // Output debug messages
    //
    if (CoreConfig.debug) {
        DebugTree.builder().name("Response Information")
                .entry("Address", workerContext.getSocketContext().getAddress())
                .entry("Headers", body.getHeader().getHeaders()).build().collect().forEach(Logger::debug);
    }

    //
    // Get the respone stream
    //
    final KvantumOutputStream responseStream = workerContext.getResponseStream(); // body.getResponseStream();
    final boolean hasKnownLength = responseStream instanceof KnownLengthStream;

    //
    // Fetch the GZIP handler, if applicable
    //
    final GzipHandler gzipHandler;
    if (workerContext.isGzip()) {
        gzipHandler = SimpleServer.gzipHandlerPool.getNullable();
    } else {
        gzipHandler = null;
    }

    boolean shouldWriteBody;
    if (workerContext.getRequest().getQuery().getMethod().hasBody()) {
        shouldWriteBody = true;
    } else {
        shouldWriteBody = false;
        body.getHeader().set(Header.HEADER_CONTENT_LENGTH, "0");
    }

    //
    // Send either the transfer encoding or content length, important for keep-alive
    //
    if (shouldWriteBody && hasKnownLength) {
        //
        // If the length is known, we compress before writing
        //
        if (workerContext.isGzip()) {
            byte[] bytes = ((KnownLengthStream) responseStream).getAll();
            try {
                bytes = gzipHandler.compress(bytes);
            } catch (final IOException e) {
                new KvantumException("( GZIP ) Failed to compress the bytes").printStackTrace();
            }
            ((KnownLengthStream) responseStream).replaceBytes(bytes);
        }
        body.getHeader().set(Header.HEADER_CONTENT_LENGTH,
                AsciiString.of(((KnownLengthStream) responseStream).getLength()));
    } else {
        body.getHeader().set(Header.HEADER_TRANSFER_ENCODING, "chunked");
    }

    //
    // Determine whether to keep the connection alive
    //
    final boolean keepAlive;
    if (workerContext.getRequest().getHeaders().getOrDefault(KvantumServerHandler.CONNECTION, CLOSE)
            .equalsIgnoreCase(KEEP_ALIVE)
            && !body.getHeader().get(Header.HEADER_CONNECTION).orElse(KEEP_ALIVE).equals(CLOSE)) {
        if (CoreConfig.debug) {
            Logger.debug("Request " + workerContext.getRequest() + " requested keep-alive...");
        }
        keepAlive = true;
        //
        // Apply "connection: keep-alive" and "content-length: n" headers to
        // make sure that the client keeps the connection open
        //
        body.getHeader().set(Header.HEADER_CONNECTION, KEEP_ALIVE);
    } else {
        keepAlive = false;
        body.getHeader().set(Header.HEADER_CONNECTION, CLOSE);
    }

    //
    // Alocate a byte buffer
    //
    final Timer.Context timerWriteToClient = KvantumServerHandler.TIMER_WRITE_TO_CLIENT.time();

    final ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(Buffer.out);

    //
    // Write the header
    //
    buf.writeBytes(body.getHeader().getFormat().getValue());
    buf.writeBytes(KvantumServerHandler.SPACE);
    buf.writeBytes(body.getHeader().getStatus().getValue());
    buf.writeBytes(KvantumServerHandler.NEW_LINE);
    for (final Map.Entry<HeaderOption, AsciiString> entry : body.getHeader().getHeaders().entries()) {
        buf.writeBytes(entry.getKey().getBytes());
        buf.writeBytes(KvantumServerHandler.COLON_SPACE);
        buf.writeBytes(entry.getValue().getValue());
        buf.writeBytes(KvantumServerHandler.NEW_LINE);
    }
    // Print one empty line to indicate that the header sending is finished, this is important as the content
    // would otherwise be classed as headers, which really isn't optimal <3
    buf.writeBytes(KvantumServerHandler.NEW_LINE);

    //
    // Write the header to the client
    //
    context.write(buf);

    long actualLength = 0L;

    if (shouldWriteBody) {
        if (CoreConfig.debug) {
            Logger.debug("Using direct write from memory: {}", hasKnownLength);
        }

        //
        // Write the response
        //
        byte[] buffer = ThreadCache.CHUNK_BUFFER.get();
        while (!responseStream.isFinished()) {
            //
            // Read as much data as possible from the respone stream
            //
            int read = responseStream.read(buffer);
            if (read != -1) {
                //
                // If the length is known, write data directly
                //
                if (hasKnownLength) {
                    context.write(Unpooled.wrappedBuffer(buffer, 0, read));
                    context.flush().newSucceededFuture().awaitUninterruptibly();
                    actualLength += read;
                } else {
                    //
                    // If the length isn't known, we first compress (if applicable) and then write using
                    // the chunked transfer encoding format
                    //
                    final ByteBuf result;

                    if (workerContext.isGzip()) {
                        try {
                            result = gzipHandler.compress(buffer, read);
                            actualLength += result.readableBytes();
                        } catch (final IOException e) {
                            new KvantumException("( GZIP ) Failed to compress the bytes").printStackTrace();
                            continue;
                        }
                    } else {
                        result = Unpooled.wrappedBuffer(buffer, 0, read);
                    }

                    actualLength += read;

                    context.write(AsciiString.of(Integer.toHexString(read)).getValue());
                    context.write(KvantumServerHandler.CRLF);
                    context.write(result);
                    context.write(KvantumServerHandler.CRLF);
                    //
                    // When using this mode we need to make sure that everything is written, so the
                    // client doesn't time out
                    //
                    context.flush().newSucceededFuture().awaitUninterruptibly();
                }
            }
        }

        //
        // If we're using the chunked encoding format
        // write the end chunk
        //
        if (!hasKnownLength) {
            context.write(KvantumServerHandler.END_CHUNK);
        }
    } /* shouldWriteToClient */ else if (CoreConfig.debug) {
        Logger.debug("Skipping body, because method {} does not require body",
                workerContext.getRequest().getQuery().getMethod());
    }

    timerWriteToClient.stop();

    //
    // Return the GZIP handler to the pool
    //
    if (gzipHandler != null) {
        SimpleServer.gzipHandlerPool.add(gzipHandler);
    }

    //
    // Invalidate request to make sure that it isn't handled anywhere else, again (wouldn't work)
    //
    workerContext.getRequest().setValid(false);

    //
    // Intialize a finalized response builder (used for logging)
    //
    final FinalizedResponse.FinalizedResponseBuilder finalizedResponse = FinalizedResponse.builder();

    //
    // Safety measure taken to make sure that IPs are not logged
    // in production mode. This is is to ensure GDPR compliance
    //
    if (CoreConfig.hideIps) {
        finalizedResponse.address(HIDDEN_IP);
    } else {
        finalizedResponse.address(this.workerContext.getSocketContext().getIP());
    }

    finalizedResponse.authorization(this.workerContext.getRequest().getAuthorization().orElse(null))
            .length((int) actualLength).status(body.getHeader().getStatus().toString())
            .query(this.workerContext.getRequest().getQuery()).timeFinished(System.currentTimeMillis()).build();

    ServerImplementation.getImplementation().getEventBus().throwEvent(finalizedResponse.build(), true);

    //
    // Make sure everything is written and either close the connection
    // or the channel (depending on whether keep-alive is used or not)
    //
    final ChannelFuture future = context.flush().newSucceededFuture();
    if (!keepAlive) {
        future.addListener(ChannelFutureListener.CLOSE);
    }

    timer.stop();
}