View Javadoc
1   /*
2    * Copyright 2016 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License, version 2.0 (the
5    * "License"); you may not use this file except in compliance with the License. You may obtain a
6    * copy of the License at:
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software distributed under the License
11   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12   * or implied. See the License for the specific language governing permissions and limitations under
13   * the License.
14   */
15  
16  package io.netty.example.http2.helloworld.frame.server;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.ByteBufUtil;
20  import io.netty.channel.ChannelDuplexHandler;
21  import io.netty.channel.ChannelHandler.Sharable;
22  import io.netty.channel.ChannelHandlerContext;
23  import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
24  import io.netty.handler.codec.http2.DefaultHttp2Headers;
25  import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
26  import io.netty.handler.codec.http2.DefaultHttp2WindowUpdateFrame;
27  import io.netty.handler.codec.http2.Http2DataFrame;
28  import io.netty.handler.codec.http2.Http2FrameStream;
29  import io.netty.handler.codec.http2.Http2Headers;
30  import io.netty.handler.codec.http2.Http2HeadersFrame;
31  import io.netty.util.CharsetUtil;
32  
33  import static io.netty.buffer.Unpooled.copiedBuffer;
34  import static io.netty.buffer.Unpooled.unreleasableBuffer;
35  import static io.netty.handler.codec.http.HttpResponseStatus.OK;
36  
37  /**
38   * A simple handler that responds with the message "Hello World!".
39   *
40   * <p>This example is making use of the "frame codec" http2 API. This API is very experimental and incomplete.
41   */
42  @Sharable
43  public class HelloWorldHttp2Handler extends ChannelDuplexHandler {
44  
45      static final ByteBuf RESPONSE_BYTES = unreleasableBuffer(copiedBuffer("Hello World", CharsetUtil.UTF_8));
46  
47      @Override
48      public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
49          super.exceptionCaught(ctx, cause);
50          cause.printStackTrace();
51          ctx.close();
52      }
53  
54      @Override
55      public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
56          if (msg instanceof Http2HeadersFrame) {
57              onHeadersRead(ctx, (Http2HeadersFrame) msg);
58          } else if (msg instanceof Http2DataFrame) {
59              onDataRead(ctx, (Http2DataFrame) msg);
60          } else {
61              super.channelRead(ctx, msg);
62          }
63      }
64  
65      @Override
66      public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
67          ctx.flush();
68      }
69  
70      /**
71       * If receive a frame with end-of-stream set, send a pre-canned response.
72       */
73      private static void onDataRead(ChannelHandlerContext ctx, Http2DataFrame data) throws Exception {
74          Http2FrameStream stream = data.stream();
75  
76          if (data.isEndStream()) {
77              sendResponse(ctx, stream, data.content());
78          } else {
79              // We do not send back the response to the remote-peer, so we need to release it.
80              data.release();
81          }
82  
83          // Update the flowcontroller
84          ctx.write(new DefaultHttp2WindowUpdateFrame(data.initialFlowControlledBytes()).stream(stream));
85      }
86  
87      /**
88       * If receive a frame with end-of-stream set, send a pre-canned response.
89       */
90      private static void onHeadersRead(ChannelHandlerContext ctx, Http2HeadersFrame headers)
91              throws Exception {
92          if (headers.isEndStream()) {
93              ByteBuf content = ctx.alloc().buffer();
94              content.writeBytes(RESPONSE_BYTES.duplicate());
95              ByteBufUtil.writeAscii(content, " - via HTTP/2");
96              sendResponse(ctx, headers.stream(), content);
97          }
98      }
99  
100     /**
101      * Sends a "Hello World" DATA frame to the client.
102      */
103     private static void sendResponse(ChannelHandlerContext ctx, Http2FrameStream stream, ByteBuf payload) {
104         // Send a frame for the response status
105         Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText());
106         ctx.write(new DefaultHttp2HeadersFrame(headers).stream(stream));
107         ctx.write(new DefaultHttp2DataFrame(payload, true).stream(stream));
108     }
109 }