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