List of usage examples for io.netty.channel ChannelHandlerContext flush
@Override ChannelHandlerContext flush();
From source file:io.enforcer.deathstar.ws.WebSocketServerHandler.java
License:Apache License
/** * Invoked when the read is complete//from ww w . j ava 2 s. c o m * * @param ctx handler context */ @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); }
From source file:io.grpc.netty.Http2ControlFrameLimitEncoder.java
License:Apache License
private ChannelPromise handleOutstandingControlFrames(ChannelHandlerContext ctx, ChannelPromise promise) { if (!limitReached) { if (outstandingControlFrames == maxOutstandingControlFrames) { // Let's try to flush once as we may be able to flush some of the control frames. ctx.flush(); }/*ww w . j a v a 2s. com*/ if (outstandingControlFrames == maxOutstandingControlFrames) { limitReached = true; Http2Exception exception = Http2Exception.connectionError(Http2Error.ENHANCE_YOUR_CALM, "Maximum number %d of outstanding control frames reached", maxOutstandingControlFrames); logger.info("Maximum number {} of outstanding control frames reached. Closing channel {}", maxOutstandingControlFrames, ctx.channel(), exception); // First notify the Http2LifecycleManager and then close the connection. lifecycleManager.onError(ctx, true, exception); ctx.close(); } outstandingControlFrames++; // We did not reach the limit yet, add the listener to decrement the number of outstanding control frames // once the promise was completed return promise.unvoid().addListener(outstandingControlFramesListener); } return promise; }
From source file:io.grpc.netty.NettyClientHandler.java
License:Apache License
/** * Sends a PING frame. If a ping operation is already outstanding, the callback in the message is * registered to be called when the existing operation completes, and no new frame is sent. *//*from ww w.j av a2s . c om*/ private void sendPingFrameTraced(ChannelHandlerContext ctx, SendPingCommand msg, ChannelPromise promise) { // Don't check lifecycleManager.getShutdownStatus() since we want to allow pings after shutdown // but before termination. After termination, messages will no longer arrive because the // pipeline clears all handlers on channel close. PingCallback callback = msg.callback(); Executor executor = msg.executor(); // we only allow one outstanding ping at a time, so just add the callback to // any outstanding operation if (ping != null) { promise.setSuccess(); ping.addCallback(callback, executor); return; } // Use a new promise to prevent calling the callback twice on write failure: here and in // NettyClientTransport.ping(). It may appear strange, but it will behave the same as if // ping != null above. promise.setSuccess(); promise = ctx().newPromise(); // set outstanding operation long data = USER_PING_PAYLOAD; Stopwatch stopwatch = stopwatchFactory.get(); stopwatch.start(); ping = new Http2Ping(data, stopwatch); ping.addCallback(callback, executor); // and then write the ping encoder().writePing(ctx, false, USER_PING_PAYLOAD, promise); ctx.flush(); final Http2Ping finalPing = ping; promise.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { transportTracer.reportKeepAliveSent(); } else { Throwable cause = future.cause(); if (cause instanceof ClosedChannelException) { cause = lifecycleManager.getShutdownThrowable(); if (cause == null) { cause = Status.UNKNOWN.withDescription("Ping failed but for unknown reason.") .withCause(future.cause()).asException(); } } finalPing.failed(cause); if (ping == finalPing) { ping = null; } } } }); }
From source file:io.grpc.netty.NettyServerHandler.java
License:Apache License
private NettyServerHandler(ChannelPromise channelUnused, final Http2Connection connection, ServerTransportListener transportListener, List<? extends ServerStreamTracer.Factory> streamTracerFactories, TransportTracer transportTracer, Http2ConnectionDecoder decoder, Http2ConnectionEncoder encoder, Http2Settings settings, int maxMessageSize, long keepAliveTimeInNanos, long keepAliveTimeoutInNanos, long maxConnectionIdleInNanos, long maxConnectionAgeInNanos, long maxConnectionAgeGraceInNanos, final KeepAliveEnforcer keepAliveEnforcer) { super(channelUnused, decoder, encoder, settings); final MaxConnectionIdleManager maxConnectionIdleManager; if (maxConnectionIdleInNanos == MAX_CONNECTION_IDLE_NANOS_DISABLED) { maxConnectionIdleManager = null; } else {// ww w .java 2s . co m maxConnectionIdleManager = new MaxConnectionIdleManager(maxConnectionIdleInNanos) { @Override void close(ChannelHandlerContext ctx) { if (gracefulShutdown == null) { gracefulShutdown = new GracefulShutdown("max_idle", null); gracefulShutdown.start(ctx); ctx.flush(); } } }; } connection.addListener(new Http2ConnectionAdapter() { @Override public void onStreamActive(Http2Stream stream) { if (connection.numActiveStreams() == 1) { keepAliveEnforcer.onTransportActive(); if (maxConnectionIdleManager != null) { maxConnectionIdleManager.onTransportActive(); } } } @Override public void onStreamClosed(Http2Stream stream) { if (connection.numActiveStreams() == 0) { keepAliveEnforcer.onTransportIdle(); if (maxConnectionIdleManager != null) { maxConnectionIdleManager.onTransportIdle(); } } } }); checkArgument(maxMessageSize >= 0, "maxMessageSize must be >= 0"); this.maxMessageSize = maxMessageSize; this.keepAliveTimeInNanos = keepAliveTimeInNanos; this.keepAliveTimeoutInNanos = keepAliveTimeoutInNanos; this.maxConnectionIdleManager = maxConnectionIdleManager; this.maxConnectionAgeInNanos = maxConnectionAgeInNanos; this.maxConnectionAgeGraceInNanos = maxConnectionAgeGraceInNanos; this.keepAliveEnforcer = checkNotNull(keepAliveEnforcer, "keepAliveEnforcer"); streamKey = encoder.connection().newKey(); this.transportListener = checkNotNull(transportListener, "transportListener"); this.streamTracerFactories = checkNotNull(streamTracerFactories, "streamTracerFactories"); this.transportTracer = checkNotNull(transportTracer, "transportTracer"); // Set the frame listener on the decoder. decoder().frameListener(new FrameListener()); }
From source file:io.grpc.netty.NettyServerHandler.java
License:Apache License
@Override public void handlerAdded(final ChannelHandlerContext ctx) throws Exception { serverWriteQueue = new WriteQueue(ctx.channel()); // init max connection age monitor if (maxConnectionAgeInNanos != MAX_CONNECTION_AGE_NANOS_DISABLED) { maxConnectionAgeMonitor = ctx.executor().schedule(new LogExceptionRunnable(new Runnable() { @Override//from w w w . j a v a2s . com public void run() { if (gracefulShutdown == null) { gracefulShutdown = new GracefulShutdown("max_age", maxConnectionAgeGraceInNanos); gracefulShutdown.start(ctx); ctx.flush(); } } }), maxConnectionAgeInNanos, TimeUnit.NANOSECONDS); } if (maxConnectionIdleManager != null) { maxConnectionIdleManager.start(ctx); } if (keepAliveTimeInNanos != SERVER_KEEPALIVE_TIME_NANOS_DISABLED) { keepAliveManager = new KeepAliveManager(new KeepAlivePinger(ctx), ctx.executor(), keepAliveTimeInNanos, keepAliveTimeoutInNanos, true /* keepAliveDuringTransportIdle */); keepAliveManager.onTransportStarted(); } if (transportTracer != null) { assert encoder().connection().equals(decoder().connection()); final Http2Connection connection = encoder().connection(); transportTracer.setFlowControlWindowReader(new TransportTracer.FlowControlReader() { private final Http2FlowController local = connection.local().flowController(); private final Http2FlowController remote = connection.remote().flowController(); @Override public TransportTracer.FlowControlWindows read() { assert ctx.executor().inEventLoop(); return new TransportTracer.FlowControlWindows(local.windowSize(connection.connectionStream()), remote.windowSize(connection.connectionStream())); } }); } super.handlerAdded(ctx); }
From source file:io.grpc.netty.NettyServerHandler.java
License:Apache License
@Override public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { if (gracefulShutdown == null) { gracefulShutdown = new GracefulShutdown("app_requested", null); gracefulShutdown.start(ctx);//from ww w .jav a 2 s. c o m ctx.flush(); } }
From source file:io.grpc.netty.WriteBufferingAndExceptionHandler.java
License:Apache License
@SuppressWarnings("FutureReturnValueIgnored") final void writeBufferedAndRemove(ChannelHandlerContext ctx) { // TODO(carl-mastrangelo): remove the isActive check and just fail if not yet ready. if (!ctx.channel().isActive() || writing) { return;// w w w.jav a2 s . co m } // Make sure that method can't be reentered, so that the ordering // in the queue can't be messed up. writing = true; while (!bufferedWrites.isEmpty()) { ChannelWrite write = bufferedWrites.poll(); ctx.write(write.msg, write.promise); } if (flushRequested) { ctx.flush(); } // Removal has to happen last as the above writes will likely trigger // new writes that have to be added to the end of queue in order to not // mess up the ordering. ctx.pipeline().remove(this); }
From source file:io.maelstorm.server.RequestHandler.java
License:Open Source License
private void sendResponse(final ChannelHandlerContext ctx, final FullHttpResponse response, final HttpRequest request) { ReferenceCountUtil.release(request); if (!ctx.channel().isActive()) { return;/*from w w w . jav a 2 s . c o m*/ } final boolean keepalive = HttpHeaders.isKeepAlive(request); if (keepalive) { HttpHeaders.setContentLength(response, response.content().readableBytes()); response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } final ChannelFuture future = ctx.write(response); ctx.flush(); if (!keepalive) { future.addListener(ChannelFutureListener.CLOSE); } }
From source file:io.syncframework.netty.RequestHandler.java
License:Apache License
private boolean sendFile(ChannelHandlerContext ctx, Response response) throws Exception { Application application = response.getApplication(); if (application == null) { log.error("no response.application has been set"); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR); return true; }/* ww w. j a v a 2 s. c o m*/ File file = response.getFile(); if (file == null) { log.error("no response.file has been set"); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR); return true; } if (!file.exists()) { // file not found try request dynamically if (log.isDebugEnabled()) log.debug("{}: file not found: {}", application, file); return false; } if (file.isHidden()) { if (log.isDebugEnabled()) { log.debug("{}: file {} is hidden; returning File Not Found", application, file.getAbsolutePath()); } sendFileNotFound(ctx); return true; } if (file.isDirectory()) { // once is a directory a dynamic handler can take it ... // even if a index.html, the @Action Controller.main() shall handle it return false; } // // Check if the file resides under the PUBLIC or PRIVATE folders. // More important point for this verification is with PUBLIC requests where multiples ../../../.. // may lead to security breach - exposing unwanted system files. // String path = file.getAbsolutePath(); if (!path.startsWith(application.getConfig().getPublicDirectory().getAbsolutePath()) && !path.startsWith(application.getConfig().getPrivateDirectory().getAbsolutePath())) { log.error("{}: file {} returned, is not located under Public or Private folders", application, file.getAbsolutePath()); sendError(ctx, HttpResponseStatus.FORBIDDEN); return true; } if (!file.isFile()) { sendError(ctx, HttpResponseStatus.FORBIDDEN); return true; } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { sendError(ctx, NOT_FOUND); return true; } long fileLength = raf.length(); if (log.isTraceEnabled()) log.trace("{}: returning file: {}", application, file); HttpResponse httpResponse = new DefaultHttpResponse(HTTP_1_1, OK); HttpUtil.setContentLength(httpResponse, fileLength); httpResponse.headers().set(CONTENT_TYPE, MimeUtils.getContentType(file)); setDateAndCacheHeaders(httpResponse, file); httpResponse.headers().set(CONNECTION, HttpHeaderValues.CLOSE); // // if response has declared specific Headers, then this may or may not override the default headers // declared above. // if (response.getHeaders() != null) { if (log.isTraceEnabled()) log.trace("custom response headers identified... passing to the response"); for (String header : response.getHeaders().keySet()) { if (log.isTraceEnabled()) log.trace("setting response header: {}: {}", header, response.getHeaders().get(header)); httpResponse.headers().set(header, response.getHeaders().get(header)); } } // Write the initial line and the header. ctx.write(httpResponse); // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; 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 if (log.isTraceEnabled()) log.trace("{}: " + future.channel() + " transfer progress: " + progress, application); } else { if (log.isTraceEnabled()) log.trace("{}: " + future.channel() + " Transfer progress: " + progress + " / " + total, application); } } @Override public void operationComplete(ChannelProgressiveFuture future) { if (log.isTraceEnabled()) log.trace("{}: " + future.channel() + " transfer complete.", application); if (raf != null) { try { raf.close(); } catch (Exception ignore) { if (log.isTraceEnabled()) log.trace("exception caught: {}", ignore); } } } }); // Close the connection when the whole content is written out. ctx.flush(); lastContentFuture.addListener(ChannelFutureListener.CLOSE); return true; }
From source file:io.vertx.benchmarks.HttpServerHandlerBenchmark.java
License:Open Source License
@Setup public void setup() { vertx = (VertxInternal) Vertx.vertx(); HttpServerOptions options = new HttpServerOptions(); vertxChannel = new EmbeddedChannel( new HttpRequestDecoder(options.getMaxInitialLineLength(), options.getMaxHeaderSize(), options.getMaxChunkSize(), false, options.getDecoderInitialBufferSize()), new HttpResponseEncoder()); vertxChannel.config().setAllocator(new Alloc()); ContextInternal context = new EventLoopContext(vertx, vertxChannel.eventLoop(), null, null, null, new JsonObject(), Thread.currentThread().getContextClassLoader()); Handler<HttpServerRequest> app = request -> { HttpServerResponse response = request.response(); MultiMap headers = response.headers(); headers.add(HEADER_CONTENT_TYPE, RESPONSE_TYPE_PLAIN).add(HEADER_SERVER, SERVER) .add(HEADER_DATE, DATE_STRING).add(HEADER_CONTENT_LENGTH, HELLO_WORLD_LENGTH); response.end(HELLO_WORLD_BUFFER); };//from w w w . j a v a 2 s.c o m HandlerHolder<HttpHandlers> holder = new HandlerHolder<>(context, new HttpHandlers(app, null, null, null)); Http1xServerHandler handler = new Http1xServerHandler(null, new HttpServerOptions(), "localhost", holder, null); vertxChannel.pipeline().addLast("handler", handler); nettyChannel = new EmbeddedChannel( new HttpRequestDecoder(options.getMaxInitialLineLength(), options.getMaxHeaderSize(), options.getMaxChunkSize(), false, options.getDecoderInitialBufferSize()), new HttpResponseEncoder(), new SimpleChannelInboundHandler<HttpRequest>() { private final byte[] STATIC_PLAINTEXT = "Hello, World!".getBytes(CharsetUtil.UTF_8); private final int STATIC_PLAINTEXT_LEN = STATIC_PLAINTEXT.length; private final ByteBuf PLAINTEXT_CONTENT_BUFFER = Unpooled .unreleasableBuffer(Unpooled.directBuffer().writeBytes(STATIC_PLAINTEXT)); private final CharSequence PLAINTEXT_CLHEADER_VALUE = new AsciiString( String.valueOf(STATIC_PLAINTEXT_LEN)); private final CharSequence TYPE_PLAIN = new AsciiString("text/plain"); private final CharSequence SERVER_NAME = new AsciiString("Netty"); private final CharSequence CONTENT_TYPE_ENTITY = HttpHeaderNames.CONTENT_TYPE; private final CharSequence DATE_ENTITY = HttpHeaderNames.DATE; private final CharSequence CONTENT_LENGTH_ENTITY = HttpHeaderNames.CONTENT_LENGTH; private final CharSequence SERVER_ENTITY = HttpHeaderNames.SERVER; private final DateFormat FORMAT = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z"); private final CharSequence date = new AsciiString(FORMAT.format(new Date())); @Override protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception { writeResponse(ctx, msg, PLAINTEXT_CONTENT_BUFFER.duplicate(), TYPE_PLAIN, PLAINTEXT_CLHEADER_VALUE); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } private void writeResponse(ChannelHandlerContext ctx, HttpRequest request, ByteBuf buf, CharSequence contentType, CharSequence contentLength) { // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf, false); HttpHeaders headers = response.headers(); headers.set(CONTENT_TYPE_ENTITY, contentType); headers.set(SERVER_ENTITY, SERVER_NAME); headers.set(DATE_ENTITY, date); headers.set(CONTENT_LENGTH_ENTITY, contentLength); // Close the non-keep-alive connection after the write operation is done. ctx.write(response, ctx.voidPromise()); } }); nettyChannel.config().setAllocator(new Alloc()); GET = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(("GET / HTTP/1.1\r\n" + "\r\n").getBytes())); readerIndex = GET.readerIndex(); writeIndex = GET.writerIndex(); }