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  package io.netty.example.http2.server;
16  
17  import io.netty.channel.ChannelHandler;
18  import io.netty.handler.codec.http2.Http2ConnectionHandler;
19  import io.netty.handler.codec.http2.Http2OrHttpChooser;
20  
21  import javax.net.ssl.SSLEngine;
22  
23  /**
24   * Negotiates with the browser if HTTP2 or HTTP is going to be used. Once decided, the Netty
25   * pipeline is setup with the correct handlers for the selected protocol.
26   */
27  public class Http2OrHttpHandler extends Http2OrHttpChooser {
28      private static final int MAX_CONTENT_LENGTH = 1024 * 100;
29  
30      public Http2OrHttpHandler() {
31          this(MAX_CONTENT_LENGTH);
32      }
33  
34      public Http2OrHttpHandler(int maxHttpContentLength) {
35          super(maxHttpContentLength);
36      }
37  
38      @Override
39      protected SelectedProtocol getProtocol(SSLEngine engine) {
40          String[] protocol = engine.getSession().getProtocol().split(":");
41          if (protocol != null && protocol.length > 1) {
42              SelectedProtocol selectedProtocol = SelectedProtocol.protocol(protocol[1]);
43              System.err.println("Selected Protocol is " + selectedProtocol);
44              return selectedProtocol;
45          }
46          return SelectedProtocol.UNKNOWN;
47      }
48  
49      @Override
50      protected ChannelHandler createHttp1RequestHandler() {
51          return new HelloWorldHttp1Handler();
52      }
53  
54      @Override
55      protected Http2ConnectionHandler createHttp2RequestHandler() {
56          return new HelloWorldHttp2Handler();
57      }
58  }