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.netty.example.http2.helloworld.frame.client;
16  
17  import io.netty.bootstrap.Bootstrap;
18  import io.netty.channel.Channel;
19  import io.netty.channel.ChannelOption;
20  import io.netty.channel.EventLoopGroup;
21  import io.netty.channel.MultiThreadIoEventLoopGroup;
22  import io.netty.channel.nio.NioIoHandler;
23  import io.netty.channel.socket.nio.NioSocketChannel;
24  import io.netty.handler.codec.http2.DefaultHttp2Headers;
25  import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
26  import io.netty.handler.codec.http2.Http2HeadersFrame;
27  import io.netty.handler.codec.http2.Http2SecurityUtil;
28  import io.netty.handler.codec.http2.Http2StreamChannel;
29  import io.netty.handler.codec.http2.Http2StreamChannelBootstrap;
30  import io.netty.handler.ssl.ApplicationProtocolConfig;
31  import io.netty.handler.ssl.ApplicationProtocolConfig.Protocol;
32  import io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior;
33  import io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior;
34  import io.netty.handler.ssl.ApplicationProtocolNames;
35  import io.netty.handler.ssl.SslContext;
36  import io.netty.handler.ssl.SslContextBuilder;
37  import io.netty.handler.ssl.SslProvider;
38  import io.netty.handler.ssl.SupportedCipherSuiteFilter;
39  import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
40  
41  /**
42   * An HTTP2 client that allows you to send HTTP2 frames to a server using the newer HTTP2
43   * approach (via {@link io.netty.handler.codec.http2.Http2FrameCodec}).
44   * When run from the command-line, sends a single HEADERS frame (with prior knowledge) to
45   * the server configured at host:port/path.
46   * You should include {@link io.netty.handler.codec.http2.Http2ClientUpgradeCodec} if the
47   * HTTP/2 server you are hitting doesn't support h2c/prior knowledge.
48   */
49  public final class Http2FrameClient {
50  
51      static final boolean SSL = System.getProperty("ssl") != null;
52      static final String HOST = System.getProperty("host", "127.0.0.1");
53      static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080"));
54      static final String PATH = System.getProperty("path", "/");
55  
56      private Http2FrameClient() {
57      }
58  
59      public static void main(String[] args) throws Exception {
60          EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
61  
62          // Configure SSL.
63          final SslContext sslCtx;
64          if (SSL) {
65              final SslProvider provider =
66                      SslProvider.isAlpnSupported(SslProvider.OPENSSL)? SslProvider.OPENSSL : SslProvider.JDK;
67              sslCtx = SslContextBuilder.forClient()
68                    .sslProvider(provider)
69                    .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
70                    // you probably won't want to use this in production, but it is fine for this example:
71                    .trustManager(InsecureTrustManagerFactory.INSTANCE)
72                    .applicationProtocolConfig(new ApplicationProtocolConfig(
73                            Protocol.ALPN,
74                            SelectorFailureBehavior.NO_ADVERTISE,
75                            SelectedListenerFailureBehavior.ACCEPT,
76                            ApplicationProtocolNames.HTTP_2,
77                            ApplicationProtocolNames.HTTP_1_1))
78                    .build();
79          } else {
80              sslCtx = null;
81          }
82  
83          try {
84              final Bootstrap b = new Bootstrap();
85              b.group(group);
86              b.channel(NioSocketChannel.class);
87              b.option(ChannelOption.SO_KEEPALIVE, true);
88              b.remoteAddress(HOST, PORT);
89              b.handler(new Http2ClientFrameInitializer(sslCtx));
90  
91              // Start the client.
92              final Channel channel = b.connect().syncUninterruptibly().channel();
93              System.out.println("Connected to [" + HOST + ':' + PORT + ']');
94  
95              final Http2ClientStreamFrameResponseHandler streamFrameResponseHandler =
96                      new Http2ClientStreamFrameResponseHandler();
97  
98              final Http2StreamChannelBootstrap streamChannelBootstrap = new Http2StreamChannelBootstrap(channel);
99              final Http2StreamChannel streamChannel = streamChannelBootstrap.open().syncUninterruptibly().getNow();
100             streamChannel.pipeline().addLast(streamFrameResponseHandler);
101 
102             // Send request (a HTTP/2 HEADERS frame - with ':method = GET' in this case)
103             final DefaultHttp2Headers headers = new DefaultHttp2Headers();
104             headers.method("GET");
105             headers.path(PATH);
106             headers.scheme(SSL? "https" : "http");
107             final Http2HeadersFrame headersFrame = new DefaultHttp2HeadersFrame(headers, true);
108             streamChannel.writeAndFlush(headersFrame);
109             System.out.println("Sent HTTP/2 GET request to " + PATH);
110 
111             // Wait for the responses (or for the latch to expire), then clean up the connections
112             if (!streamFrameResponseHandler.responseSuccessfullyCompleted()) {
113                 System.err.println("Did not get HTTP/2 response in expected time.");
114             }
115 
116             System.out.println("Finished HTTP/2 request, will close the connection.");
117 
118             // Wait until the connection is closed.
119             channel.close().syncUninterruptibly();
120         } finally {
121             group.shutdownGracefully();
122         }
123     }
124 
125 }