View Javadoc
1   /*
2    * Copyright 2020 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    * https://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.netty5.example.http2.helloworld.frame.client;
16  
17  import io.netty5.channel.Channel;
18  import io.netty5.channel.ChannelHandlerContext;
19  import io.netty5.channel.ChannelInitializer;
20  import io.netty5.channel.SimpleChannelInboundHandler;
21  import io.netty5.handler.codec.http2.Http2FrameCodec;
22  import io.netty5.handler.codec.http2.Http2FrameCodecBuilder;
23  import io.netty5.handler.codec.http2.Http2MultiplexHandler;
24  import io.netty5.handler.codec.http2.Http2Settings;
25  import io.netty5.handler.ssl.SslContext;
26  
27  /**
28   * Configures client pipeline to support HTTP/2 frames via {@link Http2FrameCodec} and {@link Http2MultiplexHandler}.
29   */
30  public final class Http2ClientFrameInitializer extends ChannelInitializer<Channel> {
31  
32      private final SslContext sslCtx;
33  
34      public Http2ClientFrameInitializer(SslContext sslCtx) {
35          this.sslCtx = sslCtx;
36      }
37  
38      @Override
39      protected void initChannel(Channel ch) throws Exception {
40          // ensure that our 'trust all' SSL handler is the first in the pipeline if SSL is enabled.
41          if (sslCtx != null) {
42              ch.pipeline().addFirst(sslCtx.newHandler(ch.bufferAllocator()));
43          }
44  
45          final Http2FrameCodec http2FrameCodec = Http2FrameCodecBuilder.forClient()
46              .initialSettings(Http2Settings.defaultSettings()) // this is the default, but shows it can be changed.
47              .build();
48          ch.pipeline().addLast(http2FrameCodec);
49          ch.pipeline().addLast(new Http2MultiplexHandler(new SimpleChannelInboundHandler<>() {
50  
51              @Override
52              protected void messageReceived(ChannelHandlerContext ctx, Object msg) {
53                  // NOOP (this is the handler for 'inbound' streams, which is not relevant in this example)
54              }
55          }));
56      }
57  
58  }