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:com.mpush.core.handler.AdminHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    ctx.write("Welcome to MPush Console [" + Utils.getLocalIp() + "]!" + EOL);
    ctx.write("since " + startTime + " has running " + startTime.until(LocalDateTime.now(), ChronoUnit.HOURS)
            + "(h)" + EOL + EOL);
    ctx.write("It is " + new Date() + " now." + EOL + EOL);
    ctx.flush();
}

From source file:com.my.netty.object.ObjectEchoClientHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    // Send the first message if this handler is a client-side handler.
    System.out.println("channel active");
    System.out.println(firstMessage.size());
    ctx.write(firstMessage);/*  www .ja  v  a  2  s .c  o  m*/
    ctx.flush();
}

From source file:com.my.netty.object.ObjectEchoServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // TODO Auto-generated method stub
    try {//  w  w w . j a v  a  2  s . c o  m
        System.out.println("server get msg" + msg.getClass());
        ctx.write("ok" + ctx.channel());
        ctx.flush();
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.mycompany.nettyweb.HttpServerHandler.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        statistics.addUniqueRequest(getIP(ctx));
        statistics.addNewRequestByIP(getIP(ctx));
        statistics.addToAllRequests();/*from ww w  . ja va2  s  .c  om*/

        HttpRequest req = (HttpRequest) msg;
        trafficURL = req.getUri();

        String uri;
        if (req.getUri().startsWith("/redirect?url=")) {
            uri = "/redirect";
        } else {
            uri = req.getUri();
        }

        switch (uri) {
        case "/hello":
            helloResponse(ctx, req);
            break;
        case "/status":
            statusResponse(ctx, req);
            break;
        case "/redirect":
            StringBuilder url = new StringBuilder(
                    new QueryStringDecoder(req.getUri()).parameters().get("url").get(0));
            if (!url.toString().startsWith("http://")) {
                url.insert(0, "http://");
            }
            statistics.addRedirects(url.toString());
            redirectResponse(ctx, url.toString());
            break;
        default:
            defResponse(ctx, req);
            break;
        }
    } else {
        ctx.flush();
    }
    setTraffic(ctx);
}

From source file:com.netty.grpc.proxy.demo.handler.GrpcProxyBackendHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    // //  ww  w. j a v a2 s.com
    Http2Settings settings = new Http2Settings();
    settings.initialWindowSize(DEFAULT_FLOW_CONTROL_WINDOW);
    settings.pushEnabled(false);
    settings.maxConcurrentStreams(0);
    ByteBuf preface = Http2CodecUtil.connectionPrefaceBuf().retainedDuplicate();
    ctx.write(preface);
    writer.writeSettings(ctx, settings, ctx.newPromise());
    writer.writeWindowUpdate(ctx, 0, 983041, ctx.newPromise());
    ctx.flush();
    ctx.read();
}

From source file:com.phei.netty.basic.TimeServerHandlerTwo.java

License:Apache License

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    System.out.println("channelReadComplete === " + ctx.handler().getClass());
    ctx.flush();
}

From source file:com.phei.netty.codec.msgpack.EchoClientHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    UserInfo[] infos = UserInfo();/*  w  w w. ja v a  2 s .  c o  m*/
    for (UserInfo infoE : infos) {
        ctx.write(infoE);
    }
    ctx.flush();
}

From source file:com.shouxun.server.netty.tcp.EchoServerHandler.java

License:Apache License

@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
    System.out.println("server channelReadComplete..." + sb.toString());
    execuseDate(sb.toString(), ctx);//from  w w w .j  a  v  a2 s  .co  m
    ctx.flush();
    sb.delete(0, sb.length());
}

From source file:com.splicemachine.stream.ResultStreamer.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    LOG.trace("Starting result streamer " + this);
    // Write init data right away
    ctx.writeAndFlush(new StreamProtocol.Init(uuid, numPartitions, partition));
    // Subsequent writes are from a separate thread, so we don't block this one
    this.future = this.workerGroup.submit(new Callable<Long>() {
        private long consumed;
        private long sent;
        private int currentBatch;

        @Override//from   w  w w  . ja v  a  2s .c o m
        public Long call() throws InterruptedException {
            org.apache.spark.TaskContext$.MODULE$.setTaskContext(taskContext);
            boolean prepared = false;
            ActivationHolder ah = null;
            if (context != null) {
                ah = ((SparkOperationContext) context).getActivationHolder();
                ah.reinitialize(null, false);
                prepared = true;
            }
            try {
                while (locatedRowIterator.hasNext()) {
                    T lr = locatedRowIterator.next();
                    consumed++;

                    ctx.write(lr, ctx.voidPromise());
                    currentBatch++;
                    sent++;

                    flushAndGetPermit();

                    if (checkLimit()) {
                        return consumed;
                    }

                    consumeOffset();
                }
                // Data has been written, request close
                ctx.writeAndFlush(new StreamProtocol.RequestClose());

                return consumed;
            } finally {
                if (prepared)
                    ah.close();
            }
        }

        /**
         * If the current batch exceeds the batch size, flush the connection and take a new permit, blocking if the client
         * hasn't had time yet to process previous messages
         */
        private void flushAndGetPermit() throws InterruptedException {
            if (currentBatch >= batchSize) {
                ctx.flush();
                currentBatch = 0;
                permits.acquire();
            }
        }

        /**
         * If the client hast told us to ignore up to 'offset' messages, consume them here. The client request can
         * arrive after we've already sent some messages.
         */
        private void consumeOffset() {
            if (consumed < offset) {
                long count = 0;
                while (locatedRowIterator.hasNext() && consumed < offset) {
                    locatedRowIterator.next();
                    count++;
                    consumed++;
                }
                ctx.writeAndFlush(new StreamProtocol.Skipped(count));
            }
        }

        /**
         * If the client told us to send no more than 'limit' messages, check it here
         * @return true if there's a limit and we reached it, false otherwise
         */
        private boolean checkLimit() {
            if (consumed > limit) {
                ctx.flush();
                if (LOG.isTraceEnabled())
                    LOG.trace("Reached limit, stopping. consumed " + consumed + " sent " + sent + " limit "
                            + limit);
                return true;
            }
            return false;
        }
    });
    active.countDown();
}

From source file:com.spotify.netty.handler.queue.AutoFlushingWriteBatcher.java

License:Apache License

/**
 * Called when the channel is opened./*  w ww  .j a va 2  s  .com*/
 */
@Override
public void connect(final ChannelHandlerContext ctx, SocketAddress remote, SocketAddress local,
        ChannelPromise promise) throws Exception {
    // Schedule a task to flush and enforce the maximum latency that a message is buffered
    flushFuture = ctx.executor().scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            final long nanosSinceLastFlush = System.nanoTime() - lastFlush;
            if (nanosSinceLastFlush > maxDelayNanos) {
                ctx.flush();
                bufferSize.set(0);
                lastFlush = System.nanoTime();
            }
        }
    }, intervalNanos, intervalNanos, NANOSECONDS);

    ctx.connect(remote, local, promise);
}