View Javadoc
1   /*
2    * Copyright 2014 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.server;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.ByteBufUtil;
20  import io.netty.channel.ChannelHandlerContext;
21  import io.netty.handler.codec.http.FullHttpRequest;
22  import io.netty.handler.codec.http.HttpHeaderNames;
23  import io.netty.handler.codec.http.HttpMethod;
24  import io.netty.handler.codec.http.HttpScheme;
25  import io.netty.handler.codec.http.HttpServerUpgradeHandler;
26  import io.netty.handler.codec.http2.DefaultHttp2Headers;
27  import io.netty.handler.codec.http2.Http2ConnectionDecoder;
28  import io.netty.handler.codec.http2.Http2ConnectionEncoder;
29  import io.netty.handler.codec.http2.Http2ConnectionHandler;
30  import io.netty.handler.codec.http2.Http2Flags;
31  import io.netty.handler.codec.http2.Http2FrameListener;
32  import io.netty.handler.codec.http2.Http2Headers;
33  import io.netty.handler.codec.http2.Http2Settings;
34  import io.netty.util.CharsetUtil;
35  
36  import static io.netty.buffer.Unpooled.copiedBuffer;
37  import static io.netty.buffer.Unpooled.unreleasableBuffer;
38  import static io.netty.handler.codec.http.HttpResponseStatus.OK;
39  
40  /**
41   * A simple handler that responds with the message "Hello World!".
42   */
43  public final class HelloWorldHttp2Handler extends Http2ConnectionHandler implements Http2FrameListener {
44  
45      static final ByteBuf RESPONSE_BYTES = unreleasableBuffer(copiedBuffer("Hello World", CharsetUtil.UTF_8));
46  
47      HelloWorldHttp2Handler(Http2ConnectionDecoder decoder, Http2ConnectionEncoder encoder,
48                             Http2Settings initialSettings) {
49          super(decoder, encoder, initialSettings);
50      }
51  
52      private static Http2Headers http1HeadersToHttp2Headers(FullHttpRequest request) {
53          CharSequence host = request.headers().get(HttpHeaderNames.HOST);
54          Http2Headers http2Headers = new DefaultHttp2Headers()
55                  .method(HttpMethod.GET.asciiName())
56                  .path(request.uri())
57                  .scheme(HttpScheme.HTTP.name());
58          if (host != null) {
59              http2Headers.authority(host);
60          }
61          return http2Headers;
62      }
63  
64      /**
65       * Handles the cleartext HTTP upgrade event. If an upgrade occurred, sends a simple response via HTTP/2
66       * on stream 1 (the stream specifically reserved for cleartext HTTP upgrade).
67       */
68      @Override
69      public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
70          if (evt instanceof HttpServerUpgradeHandler.UpgradeEvent) {
71              HttpServerUpgradeHandler.UpgradeEvent upgradeEvent =
72                      (HttpServerUpgradeHandler.UpgradeEvent) evt;
73              onHeadersRead(ctx, 1, http1HeadersToHttp2Headers(upgradeEvent.upgradeRequest()), 0 , true);
74          }
75          super.userEventTriggered(ctx, evt);
76      }
77  
78      @Override
79      public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
80          super.exceptionCaught(ctx, cause);
81          cause.printStackTrace();
82          ctx.close();
83      }
84  
85      /**
86       * Sends a "Hello World" DATA frame to the client.
87       */
88      private void sendResponse(ChannelHandlerContext ctx, int streamId, ByteBuf payload) {
89          // Send a frame for the response status
90          Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText());
91          encoder().writeHeaders(ctx, streamId, headers, 0, false, ctx.newPromise());
92          encoder().writeData(ctx, streamId, payload, 0, true, ctx.newPromise());
93  
94          // no need to call flush as channelReadComplete(...) will take care of it.
95      }
96  
97      @Override
98      public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) {
99          int processed = data.readableBytes() + padding;
100         if (endOfStream) {
101             sendResponse(ctx, streamId, data.retain());
102         }
103         return processed;
104     }
105 
106     @Override
107     public void onHeadersRead(ChannelHandlerContext ctx, int streamId,
108                               Http2Headers headers, int padding, boolean endOfStream) {
109         if (endOfStream) {
110             ByteBuf content = ctx.alloc().buffer();
111             content.writeBytes(RESPONSE_BYTES.duplicate());
112             ByteBufUtil.writeAscii(content, " - via HTTP/2");
113             sendResponse(ctx, streamId, content);
114         }
115     }
116 
117     @Override
118     public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency,
119                               short weight, boolean exclusive, int padding, boolean endOfStream) {
120         onHeadersRead(ctx, streamId, headers, padding, endOfStream);
121     }
122 
123     @Override
124     public void onPriorityRead(ChannelHandlerContext ctx, int streamId, int streamDependency,
125                                short weight, boolean exclusive) {
126     }
127 
128     @Override
129     public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode) {
130     }
131 
132     @Override
133     public void onSettingsAckRead(ChannelHandlerContext ctx) {
134     }
135 
136     @Override
137     public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) {
138     }
139 
140     @Override
141     public void onPingRead(ChannelHandlerContext ctx, ByteBuf data) {
142     }
143 
144     @Override
145     public void onPingAckRead(ChannelHandlerContext ctx, ByteBuf data) {
146     }
147 
148     @Override
149     public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId,
150                                   Http2Headers headers, int padding) {
151     }
152 
153     @Override
154     public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData) {
155     }
156 
157     @Override
158     public void onWindowUpdateRead(ChannelHandlerContext ctx, int streamId, int windowSizeIncrement) {
159     }
160 
161     @Override
162     public void onUnknownFrame(ChannelHandlerContext ctx, byte frameType, int streamId,
163                                Http2Flags flags, ByteBuf payload) {
164     }
165 }