GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Overview
  • Use
  • Tree
  • Deprecated
  • Index
  • Search
  • Help
  • io.netty.handler.codec.http2
  • Http2FrameCodec

This view

  • Original page
  • New address

GeezerVison is showing netty.io — Http2FrameCodec (Netty API Reference (4.1.141.Final))

Class Http2FrameCodec

java.lang.Object
io.netty.channel.ChannelHandlerAdapter
io.netty.channel.ChannelInboundHandlerAdapter
io.netty.handler.codec.ByteToMessageDecoder
io.netty.handler.codec.http2.Http2ConnectionHandler
io.netty.handler.codec.http2.Http2FrameCodec
All Implemented Interfaces:
ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler, Http2LifecycleManager
Direct Known Subclasses:
Http2MultiplexCodec

public class Http2FrameCodec extends Http2ConnectionHandler

An HTTP/2 handler that maps HTTP/2 frames to Http2Frame objects and vice versa. For every incoming HTTP/2 frame, an Http2Frame object is created and propagated via ByteToMessageDecoder.channelRead(ChannelHandlerContext, Object). Outbound Http2Frame objects received via write(ChannelHandlerContext, Object, ChannelPromise) are converted to the HTTP/2 wire format. HTTP/2 frames specific to a stream implement the Http2StreamFrame interface. The Http2FrameCodec is instantiated using the Http2FrameCodecBuilder. It's recommended for channel handlers to inherit from the Http2ChannelDuplexHandler, as it provides additional functionality like iterating over all active streams or creating outbound streams.

Stream Lifecycle

The frame codec delivers and writes frames for active streams. An active stream is closed when either side sends a RST_STREAM frame or both sides send a frame with the END_STREAM flag set. Each Http2StreamFrame has a Http2FrameStream object attached that uniquely identifies a particular stream.

Http2StreamFrames read from the channel always a Http2FrameStream object set, while when writing a Http2StreamFrame the application code needs to set a Http2FrameStream object using Http2StreamFrame.stream(Http2FrameStream).

Flow control

The frame codec automatically increments stream and connection flow control windows.

Incoming flow controlled frames need to be consumed by writing a Http2WindowUpdateFrame with the consumed number of bytes and the corresponding stream identifier set to the frame codec.

The local stream-level flow control window can be changed by writing a Http2SettingsFrame with the Http2Settings.initialWindowSize() set to the targeted value.

The connection-level flow control window can be changed by writing a Http2WindowUpdateFrame with the desired window size increment in bytes and the stream identifier set to 0. By default the initial connection-level flow control window is the same as initial stream-level flow control window.

New inbound Streams

The first frame of an HTTP/2 stream must be an Http2HeadersFrame, which will have an Http2FrameStream object attached.

New outbound Streams

A outbound HTTP/2 stream can be created by first instantiating a new Http2FrameStream object via Http2ChannelDuplexHandler.newStream(), and then writing a Http2HeadersFrame object with the stream attached.

    final Http2Stream2 stream = handler.newStream();
    ctx.write(headersFrame.stream(stream)).addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture f) {
            if (f.isSuccess()) {
                // Stream is active and stream.id() returns a valid stream identifier.
                System.out.println("New stream with id " + stream.id() + " created.");
            } else {
                // Stream failed to become active. Handle error.
                if (f.cause() instanceof Http2NoMoreStreamIdsException) {

                } else if (f.cause() instanceof Http2GoAwayException) {

                } else {

                }
            }
        }
    }
    

If a new stream cannot be created due to stream id exhaustion of the endpoint, the ChannelPromise of the HEADERS frame will fail with a Http2NoMoreStreamIdsException.

The HTTP/2 standard allows for an endpoint to limit the maximum number of concurrently active streams via the SETTINGS_MAX_CONCURRENT_STREAMS setting. When this limit is reached, no new streams can be created. However, the Http2FrameCodec can be build with Http2FrameCodecBuilder.encoderEnforceMaxConcurrentStreams(boolean) enabled, in which case a new stream and its associated frames will be buffered until either the limit is increased or an active stream is closed. It's, however, possible that a buffered stream will never become active. That is, the channel might get closed or a GO_AWAY frame might be received. In the first case, all writes of buffered streams will fail with a StreamBufferingEncoder.Http2ChannelClosedException. In the second case, all writes of buffered streams with an identifier less than the last stream identifier of the GO_AWAY frame will fail with a StreamBufferingEncoder.Http2GoAwayException.

Error Handling

Exceptions and errors are propagated via ChannelInboundHandler.exceptionCaught(ChannelHandlerContext, Throwable). Exceptions that apply to a specific HTTP/2 stream are wrapped in a Http2FrameStreamException and have the corresponding Http2FrameStream object attached.

Reference Counting

Some Http2StreamFrames implement the ReferenceCounted interface, as they carry reference counted objects (e.g. ByteBufs). The frame codec will call ReferenceCounted.retain() before propagating a reference counted object through the pipeline, and thus an application handler needs to release such an object after having consumed it. For more information on reference counting take a look at Reference counted objects

HTTP Upgrade

Server-side HTTP to HTTP/2 upgrade is supported in conjunction with Http2ServerUpgradeCodec; the necessary HTTP-to-HTTP/2 conversion is performed automatically.

  • Nested Class Summary

    Nested classes/interfaces inherited from class ByteToMessageDecoder

    ByteToMessageDecoder.Cumulator
    Modifier and Type
    Class
    Description
    static interface 
    ByteToMessageDecoder.Cumulator
    Cumulate ByteBufs.

    Nested classes/interfaces inherited from interface ChannelHandler

    ChannelHandler.Sharable
    Modifier and Type
    Interface
    Description
    static @interface 
    ChannelHandler.Sharable
    Indicates that the same instance of the annotated ChannelHandler can be added to one or more ChannelPipelines multiple times without a race condition.
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    protected final Http2Connection.PropertyKey
    streamKey
     

    Fields inherited from class ByteToMessageDecoder

    COMPOSITE_CUMULATOR, MERGE_CUMULATOR
    Modifier and Type
    Field
    Description
    static final ByteToMessageDecoder.Cumulator
    COMPOSITE_CUMULATOR
    Cumulate ByteBufs by add them to a CompositeByteBuf and so do no memory copy whenever possible.
    static final ByteToMessageDecoder.Cumulator
    MERGE_CUMULATOR
    Cumulate ByteBufs by merge them into one ByteBuf's, using memory copies.
  • Constructor Summary

    Constructors
    Modifier
    Constructor
    Description
    protected
    Http2FrameCodec(Http2ConnectionEncoder encoder, Http2ConnectionDecoder decoder, Http2Settings initialSettings, boolean decoupleCloseAndGoAway, boolean flushPreface)
     
  • Method Summary

    Modifier and Type
    Method
    Description
    final void
    handlerAdded(ChannelHandlerContext ctx)
    Do nothing by default, sub-classes may override this method.
    protected final boolean
    isGracefulShutdownComplete()
    Called by the graceful shutdown logic to determine when it is safe to close the connection.
    protected Http2StreamFrame
    newHttp2UnknownFrame(byte frameType, int streamId, Http2Flags flags, ByteBuf payload)
    Create a Http2UnknownFrame.
    protected void
    onConnectionError(ChannelHandlerContext ctx, boolean outbound, Throwable cause, Http2Exception http2Ex)
    Handler for a connection error.
    protected final void
    onStreamError(ChannelHandlerContext ctx, boolean outbound, Throwable cause, Http2Exception.StreamException streamException)
    Exceptions for unknown streams, that is streams that have no Http2FrameStream object attached are simply logged and replied to by sending a RST_STREAM frame.
    final void
    userEventTriggered(ChannelHandlerContext ctx, Object evt)
    Handles the cleartext HTTP upgrade event.
    void
    write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
    Processes all Http2Frames.

    Methods inherited from class Http2ConnectionHandler

    bind, channelActive, channelInactive, channelReadComplete, channelWritabilityChanged, close, closeStream, closeStreamLocal, closeStreamRemote, connect, connection, decode, decoder, deregister, disconnect, encoder, exceptionCaught, flush, frameWriter, goAway, gracefulShutdownTimeoutMillis, gracefulShutdownTimeoutMillis, handlerRemoved0, handleServerHeaderDecodeSizeError, onError, onHttpClientUpgrade, onHttpServerUpgrade, read, resetStream
    Modifier and Type
    Method
    Description
    void
    bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise)
    Called once a bind operation is made.
    void
    channelActive(ChannelHandlerContext ctx)
    Calls ChannelHandlerContext.fireChannelActive() to forward to the next ChannelInboundHandler in the ChannelPipeline.
    void
    channelInactive(ChannelHandlerContext ctx)
    Calls ChannelHandlerContext.fireChannelInactive() to forward to the next ChannelInboundHandler in the ChannelPipeline.
    void
    channelReadComplete(ChannelHandlerContext ctx)
    Calls ChannelHandlerContext.fireChannelReadComplete() to forward to the next ChannelInboundHandler in the ChannelPipeline.
    void
    channelWritabilityChanged(ChannelHandlerContext ctx)
    Calls ChannelHandlerContext.fireChannelWritabilityChanged() to forward to the next ChannelInboundHandler in the ChannelPipeline.
    void
    close(ChannelHandlerContext ctx, ChannelPromise promise)
    Called once a close operation is made.
    void
    closeStream(Http2Stream stream, ChannelFuture future)
    Closes and deactivates the given stream.
    void
    closeStreamLocal(Http2Stream stream, ChannelFuture future)
    Closes the local side of the given stream.
    void
    closeStreamRemote(Http2Stream stream, ChannelFuture future)
    Closes the remote side of the given stream.
    void
    connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise)
    Called once a connect operation is made.
    Http2Connection
    connection()
     
    protected void
    decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
    Decode the from one ByteBuf to an other.
    Http2ConnectionDecoder
    decoder()
     
    void
    deregister(ChannelHandlerContext ctx, ChannelPromise promise)
    Called once a deregister operation is made from the current registered EventLoop.
    void
    disconnect(ChannelHandlerContext ctx, ChannelPromise promise)
    Called once a disconnect operation is made.
    Http2ConnectionEncoder
    encoder()
     
    void
    exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
    Handles Http2Exception objects that were thrown from other handlers.
    void
    flush(ChannelHandlerContext ctx)
    Called once a flush operation is made.
    protected Http2FrameWriter
    frameWriter()
     
    ChannelFuture
    goAway(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData, ChannelPromise promise)
    Prevents the peer from creating streams and close the connection if errorCode is not Http2Error.NO_ERROR.
    long
    gracefulShutdownTimeoutMillis()
    Get the amount of time (in milliseconds) this endpoint will wait for all streams to be closed before closing the connection during the graceful shutdown process.
    void
    gracefulShutdownTimeoutMillis(long gracefulShutdownTimeoutMillis)
    Set the amount of time (in milliseconds) this endpoint will wait for all streams to be closed before closing the connection during the graceful shutdown process.
    protected void
    handlerRemoved0(ChannelHandlerContext ctx)
    Gets called after the ByteToMessageDecoder was removed from the actual context and it doesn't handle events anymore.
    protected void
    handleServerHeaderDecodeSizeError(ChannelHandlerContext ctx, Http2Stream stream)
    Notifies client that this server has received headers that are larger than what it is willing to accept.
    void
    onError(ChannelHandlerContext ctx, boolean outbound, Throwable cause)
    Central handler for all exceptions caught during HTTP/2 processing.
    void
    onHttpClientUpgrade()
    Handles the client-side (cleartext) upgrade from HTTP to HTTP/2.
    void
    onHttpServerUpgrade(Http2Settings settings)
    Handles the server-side (cleartext) upgrade from HTTP to HTTP/2.
    void
    read(ChannelHandlerContext ctx)
    Intercepts ChannelHandlerContext.read().
    ChannelFuture
    resetStream(ChannelHandlerContext ctx, int streamId, long errorCode, ChannelPromise promise)
    Ensure the stream identified by streamId is reset.

    Methods inherited from class ByteToMessageDecoder

    actualReadableBytes, callDecode, channelRead, decodeLast, discardSomeReadBytes, handlerRemoved, internalBuffer, isSingleDecode, setCumulator, setDiscardAfterReads, setSingleDecode
    Modifier and Type
    Method
    Description
    protected int
    actualReadableBytes()
    Returns the actual number of readable bytes in the internal cumulative buffer of this decoder.
    protected void
    callDecode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
    Called once data should be decoded from the given ByteBuf.
    void
    channelRead(ChannelHandlerContext ctx, Object input)
    Calls ChannelHandlerContext.fireChannelRead(Object) to forward to the next ChannelInboundHandler in the ChannelPipeline.
    protected void
    decodeLast(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
    Is called one last time when the ChannelHandlerContext goes in-active.
    protected final void
    discardSomeReadBytes()
     
    final void
    handlerRemoved(ChannelHandlerContext ctx)
    Do nothing by default, sub-classes may override this method.
    protected ByteBuf
    internalBuffer()
    Returns the internal cumulative buffer of this decoder.
    boolean
    isSingleDecode()
    If true then only one message is decoded on each ByteToMessageDecoder.channelRead(ChannelHandlerContext, Object) call.
    void
    setCumulator(ByteToMessageDecoder.Cumulator cumulator)
    Set the ByteToMessageDecoder.Cumulator to use for cumulate the received ByteBufs.
    void
    setDiscardAfterReads(int discardAfterReads)
    Set the number of reads after which ByteBuf.discardSomeReadBytes() are called and so free up memory.
    void
    setSingleDecode(boolean singleDecode)
    If set then only one message is decoded on each ByteToMessageDecoder.channelRead(ChannelHandlerContext, Object) call.

    Methods inherited from class ChannelInboundHandlerAdapter

    channelRegistered, channelUnregistered
    Modifier and Type
    Method
    Description
    void
    channelRegistered(ChannelHandlerContext ctx)
    Calls ChannelHandlerContext.fireChannelRegistered() to forward to the next ChannelInboundHandler in the ChannelPipeline.
    void
    channelUnregistered(ChannelHandlerContext ctx)
    Calls ChannelHandlerContext.fireChannelUnregistered() to forward to the next ChannelInboundHandler in the ChannelPipeline.

    Methods inherited from class ChannelHandlerAdapter

    ensureNotSharable, isSharable
    Modifier and Type
    Method
    Description
    protected void
    ensureNotSharable()
    Throws IllegalStateException if ChannelHandlerAdapter.isSharable() returns true
    boolean
    isSharable()
    Return true if the implementation is ChannelHandler.Sharable and so can be added to different ChannelPipelines.

    Methods inherited from class Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • streamKey

      protected final Http2Connection.PropertyKey streamKey
  • Constructor Details

    • Http2FrameCodec

      protected Http2FrameCodec(Http2ConnectionEncoder encoder, Http2ConnectionDecoder decoder, Http2Settings initialSettings, boolean decoupleCloseAndGoAway, boolean flushPreface)
  • Method Details

    • handlerAdded

      public final void handlerAdded(ChannelHandlerContext ctx) throws Exception
      Description copied from class: ChannelHandlerAdapter
      Do nothing by default, sub-classes may override this method.
      Specified by:
      handlerAdded in interface ChannelHandler
      Overrides:
      handlerAdded in class Http2ConnectionHandler
      Throws:
      Exception
    • userEventTriggered

      public final void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception
      Handles the cleartext HTTP upgrade event. If an upgrade occurred, sends a simple response via HTTP/2 on stream 1 (the stream specifically reserved for cleartext HTTP upgrade).
      Specified by:
      userEventTriggered in interface ChannelInboundHandler
      Overrides:
      userEventTriggered in class ByteToMessageDecoder
      Throws:
      Exception
    • write

      public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
      Processes all Http2Frames. Http2StreamFrames may only originate in child streams.
      Specified by:
      write in interface ChannelOutboundHandler
      Overrides:
      write in class Http2ConnectionHandler
      Parameters:
      ctx - the ChannelHandlerContext for which the write operation is made
      msg - the message to write
      promise - the ChannelPromise to notify once the operation completes
    • onConnectionError

      protected void onConnectionError(ChannelHandlerContext ctx, boolean outbound, Throwable cause, Http2Exception http2Ex)
      Description copied from class: Http2ConnectionHandler
      Handler for a connection error. Sends a GO_AWAY frame to the remote endpoint. Once all streams are closed, the connection is shut down.
      Overrides:
      onConnectionError in class Http2ConnectionHandler
      Parameters:
      ctx - the channel context
      outbound - true if the error was caused by an outbound operation.
      cause - the exception that was caught
      http2Ex - the Http2Exception that is embedded in the causality chain. This may be null if it's an unknown exception.
    • onStreamError

      protected final void onStreamError(ChannelHandlerContext ctx, boolean outbound, Throwable cause, Http2Exception.StreamException streamException)
      Exceptions for unknown streams, that is streams that have no Http2FrameStream object attached are simply logged and replied to by sending a RST_STREAM frame.
      Overrides:
      onStreamError in class Http2ConnectionHandler
      Parameters:
      ctx - the channel context
      outbound - true if the error was caused by an outbound operation.
      cause - the exception that was caught
      streamException - the Http2Exception.StreamException that is embedded in the causality chain.
    • isGracefulShutdownComplete

      protected final boolean isGracefulShutdownComplete()
      Description copied from class: Http2ConnectionHandler
      Called by the graceful shutdown logic to determine when it is safe to close the connection. Returns true if the graceful shutdown has completed and the connection can be safely closed. This implementation just guarantees that there are no active streams. Subclasses may override to provide additional checks.
      Overrides:
      isGracefulShutdownComplete in class Http2ConnectionHandler
    • newHttp2UnknownFrame

      protected Http2StreamFrame newHttp2UnknownFrame(byte frameType, int streamId, Http2Flags flags, ByteBuf payload)
      Create a Http2UnknownFrame. The ownership of the ByteBuf is transferred.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.