Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "HttpRequest", "FullHttpRequest", "HttpMessage", "FullHttpMessage" and "LastHttpContent"?

Tags:

netty

I am trying to use netty to write some HTTP application. But I am confused by the so many similar types:

  • HttpRequest
  • FullHttpRequest
  • HttpMessage
  • FullHttpMessage
  • HttpResponse
  • FullHttpResponse
  • LastHttpContent

I guess I lack an understanding of netty's design philosophy behind this.

Could anyone shed some light?

like image 555
smwikipedia Avatar asked Mar 23 '15 15:03

smwikipedia


1 Answers

When an HTTP message is decoded by an HttpObjectDecoder, the decoder produces the following objects:

  1. An HttpRequest or an HttpResponse that provides the properties decoded from the initial line and its following headers.
  2. A series of HttpContent. The last HttpContent is LastHttpContent.

A typical handler code will look like the following:

if (msg instanceof HttpRequest) {
    ...
}
if (msg instanceof HttpContent) {
    ...
    if (msg instanceof LastHttpContent) {
        ...
    }
}

Please note that the if blocks are not mutually exclusive and thus the handler does not return when one of the 3 conditions above is met. Take a look into HttpSnoopServerHandler for a concrete example.

Now, let's take a look at FullHttpRequest. It implements HttpRequest, HttpContent, and LastHttpContent. The well-written handler should just work when we inserted HttpObjectAggregator into the pipeline without changing any code.

So, the intention of this weird-looking class hierarchy is to enable a user to choose to use HttpObjectAggregator or not.

However, I do agree this is not intuitive. We are going to fix this in Netty 5 in such a way that the decoder produces only a single HTTP message object and streaming its content to it later.

like image 157
trustin Avatar answered Oct 26 '22 04:10

trustin