netty5/example/src/main/java/io/netty/example/spdy/client/SpdyClient.java

106 lines
4.8 KiB
Java
Raw Normal View History

/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.example.spdy.client;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
Decouple EventLoop details from the IO handling for each transport to… (#8680) * Decouble EventLoop details from the IO handling for each transport to allow easy re-use of code and customization Motiviation: As today extending EventLoop implementations to add custom logic / metrics / instrumentations is only possible in a very limited way if at all. This is due the fact that most implementations are final or even package-private. That said even if these would be public there are the ability to do something useful with these is very limited as the IO processing and task processing are very tightly coupled. All of the mentioned things are a big pain point in netty 4.x and need improvement. Modifications: This changeset decoubled the IO processing logic from the task processing logic for the main transport (NIO, Epoll, KQueue) by introducing the concept of an IoHandler. The IoHandler itself is responsible to wait for IO readiness and process these IO events. The execution of the IoHandler itself is done by the SingleThreadEventLoop as part of its EventLoop processing. This allows to use the same EventLoopGroup (MultiThreadEventLoupGroup) for all the mentioned transports by just specify a different IoHandlerFactory during construction. Beside this core API change this changeset also allows to easily extend SingleThreadEventExecutor / SingleThreadEventLoop to add custom logic to it which then can be reused by all the transports. The ideas are very similar to what is provided by ScheduledThreadPoolExecutor (that is part of the JDK). This allows for example things like: * Adding instrumentation / metrics: * how many Channels are registered on an SingleThreadEventLoop * how many Channels were handled during the IO processing in an EventLoop run * how many task were handled during the last EventLoop / EventExecutor run * how many outstanding tasks we have ... ... * Implementing custom strategies for choosing the next EventExecutor / EventLoop to use based on these metrics. * Use different Promise / Future / ScheduledFuture implementations * decorate Runnable / Callables when submitted to the EventExecutor / EventLoop As a lot of functionalities are folded into the MultiThreadEventLoopGroup and SingleThreadEventLoopGroup this changeset also removes: * AbstractEventLoop * AbstractEventLoopGroup * EventExecutorChooser * EventExecutorChooserFactory * DefaultEventLoopGroup * DefaultEventExecutor * DefaultEventExecutorGroup Result: Fixes https://github.com/netty/netty/issues/8514 .
2019-01-23 08:32:05 +01:00
import io.netty.channel.MultithreadEventLoopGroup;
import io.netty.channel.nio.NioHandler;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
Fix backward compatibility from the previous backport Motivation: The commit 50e06442c3f2753c9b2a506f68ea70273b829e21 changed the type of the constants in HttpHeaders.Names and HttpHeaders.Values, making 4.1 backward-incompatible with 4.0. It also introduces newer utility classes such as HttpHeaderUtil, which deprecates most static methods in HttpHeaders. To ease the migration between 4.1 and 5.0, we should deprecate all static methods that are non-existent in 5.0, and provide proper counterpart. Modification: - Revert the changes in HttpHeaders.Names and Values - Deprecate all static methods in HttpHeaders in favor of: - HttpHeaderUtil - the member methods of HttpHeaders - AsciiString - Add integer and date access methods to HttpHeaders for easier future migration to 5.0 - Add HttpHeaderNames and HttpHeaderValues which provide standard HTTP constants in AsciiString - Deprecate HttpHeaders.Names and Values - Make HttpHeaderValues.WEBSOCKET lowercased because it's actually lowercased in all WebSocket versions but the oldest one - Add RtspHeaderNames and RtspHeaderValues which provide standard RTSP constants in AsciiString - Deprecate RtspHeaders.* - Do not use AsciiString.equalsIgnoreCase(CharSeq, CharSeq) if one of the parameters are AsciiString - Avoid using AsciiString.toString() repetitively - Change the parameter type of some methods from String to CharSequence Result: Backward compatibility is recovered. New classes and methods will make the migration to 5.0 easier, once (Http|Rtsp)Header(Names|Values) are ported to master.
2014-10-31 08:48:28 +01:00
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.ssl.ApplicationProtocolConfig;
import io.netty.handler.ssl.ApplicationProtocolConfig.Protocol;
import io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior;
import io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior;
import io.netty.handler.ssl.ApplicationProtocolNames;
Add an OpenSslEngine and the universal API for enabling SSL Motivation: Some users already use an SSLEngine implementation in finagle-native. It wraps OpenSSL to get higher SSL performance. However, to take advantage of it, finagle-native must be compiled manually, and it means we cannot pull it in as a dependency and thus we cannot test our SslHandler against the OpenSSL-based SSLEngine. For an instance, we had #2216. Because the construction procedures of JDK SSLEngine and OpenSslEngine are very different from each other, we also need to provide a universal way to enable SSL in a Netty application. Modifications: - Pull netty-tcnative in as an optional dependency. http://netty.io/wiki/forked-tomcat-native.html - Backport NativeLibraryLoader from 4.0 - Move OpenSSL-based SSLEngine implementation into our code base. - Copied from finagle-native; originally written by @jpinner et al. - Overall cleanup by @trustin. - Run all SslHandler tests with both default SSLEngine and OpenSslEngine - Add a unified API for creating an SSL context - SslContext allows you to create a new SSLEngine or a new SslHandler with your PKCS#8 key and X.509 certificate chain. - Add JdkSslContext and its subclasses - Add OpenSslServerContext - Add ApplicationProtocolSelector to ensure the future support for NPN (NextProtoNego) and ALPN (Application Layer Protocol Negotiation) on the client-side. - Add SimpleTrustManagerFactory to help a user write a TrustManagerFactory easily, which should be useful for those who need to write an alternative verification mechanism. For example, we can use it to implement an unsafe TrustManagerFactory that accepts self-signed certificates for testing purposes. - Add InsecureTrustManagerFactory and FingerprintTrustManager for quick and dirty testing - Add SelfSignedCertificate class which generates a self-signed X.509 certificate very easily. - Update all our examples to use SslContext.newClient/ServerContext() - SslHandler now logs the chosen cipher suite when handshake is finished. Result: - Cleaner unified API for configuring an SSL client and an SSL server regardless of its internal implementation. - When native libraries are available, OpenSSL-based SSLEngine implementation is selected automatically to take advantage of its performance benefit. - Examples take advantage of this modification and thus are cleaner.
2014-05-17 19:26:01 +02:00
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
Add an OpenSslEngine and the universal API for enabling SSL Motivation: Some users already use an SSLEngine implementation in finagle-native. It wraps OpenSSL to get higher SSL performance. However, to take advantage of it, finagle-native must be compiled manually, and it means we cannot pull it in as a dependency and thus we cannot test our SslHandler against the OpenSSL-based SSLEngine. For an instance, we had #2216. Because the construction procedures of JDK SSLEngine and OpenSslEngine are very different from each other, we also need to provide a universal way to enable SSL in a Netty application. Modifications: - Pull netty-tcnative in as an optional dependency. http://netty.io/wiki/forked-tomcat-native.html - Backport NativeLibraryLoader from 4.0 - Move OpenSSL-based SSLEngine implementation into our code base. - Copied from finagle-native; originally written by @jpinner et al. - Overall cleanup by @trustin. - Run all SslHandler tests with both default SSLEngine and OpenSslEngine - Add a unified API for creating an SSL context - SslContext allows you to create a new SSLEngine or a new SslHandler with your PKCS#8 key and X.509 certificate chain. - Add JdkSslContext and its subclasses - Add OpenSslServerContext - Add ApplicationProtocolSelector to ensure the future support for NPN (NextProtoNego) and ALPN (Application Layer Protocol Negotiation) on the client-side. - Add SimpleTrustManagerFactory to help a user write a TrustManagerFactory easily, which should be useful for those who need to write an alternative verification mechanism. For example, we can use it to implement an unsafe TrustManagerFactory that accepts self-signed certificates for testing purposes. - Add InsecureTrustManagerFactory and FingerprintTrustManager for quick and dirty testing - Add SelfSignedCertificate class which generates a self-signed X.509 certificate very easily. - Update all our examples to use SslContext.newClient/ServerContext() - SslHandler now logs the chosen cipher suite when handshake is finished. Result: - Cleaner unified API for configuring an SSL client and an SSL server regardless of its internal implementation. - When native libraries are available, OpenSSL-based SSLEngine implementation is selected automatically to take advantage of its performance benefit. - Examples take advantage of this modification and thus are cleaner.
2014-05-17 19:26:01 +02:00
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
/**
* An SPDY client that allows you to send HTTP GET to a SPDY server.
* <p>
* This class must be run with the JVM parameter: {@code java -Xbootclasspath/p:<path_to_npn_boot_jar> ...}. The
* "path_to_npn_boot_jar" is the path on the file system for the NPN Boot Jar file which can be downloaded from Maven at
* coordinates org.mortbay.jetty.npn:npn-boot. Different versions applies to different OpenJDK versions. See
* <a href="http://www.eclipse.org/jetty/documentation/current/npn-chapter.html">Jetty docs</a> for more information.
* <p>
* You may also use the {@code run-example.sh} script to start the client from the command line:
* <pre>
* ./run-example.sh spdy-client
* </pre>
*/
public final class SpdyClient {
static final String HOST = System.getProperty("host", "127.0.0.1");
Improve the API design of Http2OrHttpChooser and SpdyOrHttpChooser Related: #3641 and #3813 Motivation: When setting up an HTTP/1 or HTTP/2 (or SPDY) pipeline, a user usually ends up with adding arbitrary set of handlers. Http2OrHttpChooser and SpdyOrHttpChooser have two abstract methods (create*Handler()) that expect a user to return a single handler, and also have add*Handlers() methods that add the handler returned by create*Handler() to the pipeline as well as the pre-defined set of handlers. The problem is, some users (read: I) don't need all of them or the user wants to add more than one handler. For example, take a look at io.netty.example.http2.tiles.Http2OrHttpHandler, which works around this issue by overriding addHttp2Handlers() and making createHttp2RequestHandler() a no-op. Modifications: - Replace add*Handlers() and create*Handler() with configure*() - Rename getProtocol() to selectProtocol() to make what it does clear - Provide the default implementation of selectProtocol() - Remove SelectedProtocol.UNKNOWN and use null instead, because 'UNKNOWN' is not a protocol - Proper exception handling in the *OrHttpChooser so that the exception is logged and the connection is closed when failed to select a protocol - Make SpdyClient example always use SSL. It was always using SSL anyway. - Implement SslHandshakeCompletionEvent.toString() for debuggability - Remove an orphaned class: JettyNpnSslSession - Add SslHandler.applicationProtocol() to get the name of the application protocol - SSLSession.getProtocol() now returns transport-layer protocol name only, so that it conforms to its contract. Result: - *OrHttpChooser have better API. - *OrHttpChooser handle protocol selection failure properly. - SSLSession.getProtocol() now conforms to its contract. - SpdyClient example works with SpdyServer example out of the box
2015-05-30 10:53:46 +02:00
static final int PORT = Integer.parseInt(System.getProperty("port", "8443"));
public static void main(String[] args) throws Exception {
// Configure SSL.
final SslContext sslCtx = SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.applicationProtocolConfig(new ApplicationProtocolConfig(
Protocol.NPN,
// NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
SelectorFailureBehavior.NO_ADVERTISE,
// ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
SelectedListenerFailureBehavior.ACCEPT,
ApplicationProtocolNames.SPDY_3_1,
ApplicationProtocolNames.HTTP_1_1))
.build();
HttpResponseClientHandler httpResponseHandler = new HttpResponseClientHandler();
Decouple EventLoop details from the IO handling for each transport to… (#8680) * Decouble EventLoop details from the IO handling for each transport to allow easy re-use of code and customization Motiviation: As today extending EventLoop implementations to add custom logic / metrics / instrumentations is only possible in a very limited way if at all. This is due the fact that most implementations are final or even package-private. That said even if these would be public there are the ability to do something useful with these is very limited as the IO processing and task processing are very tightly coupled. All of the mentioned things are a big pain point in netty 4.x and need improvement. Modifications: This changeset decoubled the IO processing logic from the task processing logic for the main transport (NIO, Epoll, KQueue) by introducing the concept of an IoHandler. The IoHandler itself is responsible to wait for IO readiness and process these IO events. The execution of the IoHandler itself is done by the SingleThreadEventLoop as part of its EventLoop processing. This allows to use the same EventLoopGroup (MultiThreadEventLoupGroup) for all the mentioned transports by just specify a different IoHandlerFactory during construction. Beside this core API change this changeset also allows to easily extend SingleThreadEventExecutor / SingleThreadEventLoop to add custom logic to it which then can be reused by all the transports. The ideas are very similar to what is provided by ScheduledThreadPoolExecutor (that is part of the JDK). This allows for example things like: * Adding instrumentation / metrics: * how many Channels are registered on an SingleThreadEventLoop * how many Channels were handled during the IO processing in an EventLoop run * how many task were handled during the last EventLoop / EventExecutor run * how many outstanding tasks we have ... ... * Implementing custom strategies for choosing the next EventExecutor / EventLoop to use based on these metrics. * Use different Promise / Future / ScheduledFuture implementations * decorate Runnable / Callables when submitted to the EventExecutor / EventLoop As a lot of functionalities are folded into the MultiThreadEventLoopGroup and SingleThreadEventLoopGroup this changeset also removes: * AbstractEventLoop * AbstractEventLoopGroup * EventExecutorChooser * EventExecutorChooserFactory * DefaultEventLoopGroup * DefaultEventExecutor * DefaultEventExecutorGroup Result: Fixes https://github.com/netty/netty/issues/8514 .
2019-01-23 08:32:05 +01:00
EventLoopGroup workerGroup = new MultithreadEventLoopGroup(NioHandler.newFactory());
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.remoteAddress(HOST, PORT);
b.handler(new SpdyClientInitializer(sslCtx, httpResponseHandler));
// Start the client.
Channel channel = b.connect().syncUninterruptibly().channel();
System.out.println("Connected to " + HOST + ':' + PORT);
// Create a GET request.
HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
Fix backward compatibility from the previous backport Motivation: The commit 50e06442c3f2753c9b2a506f68ea70273b829e21 changed the type of the constants in HttpHeaders.Names and HttpHeaders.Values, making 4.1 backward-incompatible with 4.0. It also introduces newer utility classes such as HttpHeaderUtil, which deprecates most static methods in HttpHeaders. To ease the migration between 4.1 and 5.0, we should deprecate all static methods that are non-existent in 5.0, and provide proper counterpart. Modification: - Revert the changes in HttpHeaders.Names and Values - Deprecate all static methods in HttpHeaders in favor of: - HttpHeaderUtil - the member methods of HttpHeaders - AsciiString - Add integer and date access methods to HttpHeaders for easier future migration to 5.0 - Add HttpHeaderNames and HttpHeaderValues which provide standard HTTP constants in AsciiString - Deprecate HttpHeaders.Names and Values - Make HttpHeaderValues.WEBSOCKET lowercased because it's actually lowercased in all WebSocket versions but the oldest one - Add RtspHeaderNames and RtspHeaderValues which provide standard RTSP constants in AsciiString - Deprecate RtspHeaders.* - Do not use AsciiString.equalsIgnoreCase(CharSeq, CharSeq) if one of the parameters are AsciiString - Avoid using AsciiString.toString() repetitively - Change the parameter type of some methods from String to CharSequence Result: Backward compatibility is recovered. New classes and methods will make the migration to 5.0 easier, once (Http|Rtsp)Header(Names|Values) are ported to master.
2014-10-31 08:48:28 +01:00
request.headers().set(HttpHeaderNames.HOST, HOST);
request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
// Send the GET request.
channel.writeAndFlush(request).sync();
// Waits for the complete HTTP response
httpResponseHandler.queue().take().sync();
System.out.println("Finished SPDY HTTP GET");
// Wait until the connection is closed.
channel.close().syncUninterruptibly();
} finally {
Improve the API design of Http2OrHttpChooser and SpdyOrHttpChooser Related: #3641 and #3813 Motivation: When setting up an HTTP/1 or HTTP/2 (or SPDY) pipeline, a user usually ends up with adding arbitrary set of handlers. Http2OrHttpChooser and SpdyOrHttpChooser have two abstract methods (create*Handler()) that expect a user to return a single handler, and also have add*Handlers() methods that add the handler returned by create*Handler() to the pipeline as well as the pre-defined set of handlers. The problem is, some users (read: I) don't need all of them or the user wants to add more than one handler. For example, take a look at io.netty.example.http2.tiles.Http2OrHttpHandler, which works around this issue by overriding addHttp2Handlers() and making createHttp2RequestHandler() a no-op. Modifications: - Replace add*Handlers() and create*Handler() with configure*() - Rename getProtocol() to selectProtocol() to make what it does clear - Provide the default implementation of selectProtocol() - Remove SelectedProtocol.UNKNOWN and use null instead, because 'UNKNOWN' is not a protocol - Proper exception handling in the *OrHttpChooser so that the exception is logged and the connection is closed when failed to select a protocol - Make SpdyClient example always use SSL. It was always using SSL anyway. - Implement SslHandshakeCompletionEvent.toString() for debuggability - Remove an orphaned class: JettyNpnSslSession - Add SslHandler.applicationProtocol() to get the name of the application protocol - SSLSession.getProtocol() now returns transport-layer protocol name only, so that it conforms to its contract. Result: - *OrHttpChooser have better API. - *OrHttpChooser handle protocol selection failure properly. - SSLSession.getProtocol() now conforms to its contract. - SpdyClient example works with SpdyServer example out of the box
2015-05-30 10:53:46 +02:00
workerGroup.shutdownGracefully();
}
}
}