1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.netty.example.http2.helloworld.multiplex.server;
18
19 import io.netty.bootstrap.ServerBootstrap;
20 import io.netty.channel.Channel;
21 import io.netty.channel.ChannelOption;
22 import io.netty.channel.EventLoopGroup;
23 import io.netty.channel.nio.NioEventLoopGroup;
24 import io.netty.channel.socket.nio.NioServerSocketChannel;
25 import io.netty.handler.codec.http2.Http2SecurityUtil;
26 import io.netty.handler.logging.LogLevel;
27 import io.netty.handler.logging.LoggingHandler;
28 import io.netty.handler.ssl.ApplicationProtocolConfig;
29 import io.netty.handler.ssl.ApplicationProtocolConfig.Protocol;
30 import io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior;
31 import io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior;
32 import io.netty.handler.ssl.ApplicationProtocolNames;
33 import io.netty.handler.ssl.OpenSsl;
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.SelfSignedCertificate;
39
40
41
42
43
44
45
46
47 public final class Http2Server {
48
49 static final boolean SSL = System.getProperty("ssl") != null;
50
51 static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080"));
52
53 public static void main(String[] args) throws Exception {
54
55 final SslContext sslCtx;
56 if (SSL) {
57 SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
58 SelfSignedCertificate ssc = new SelfSignedCertificate();
59 sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
60 .sslProvider(provider)
61
62
63 .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
64 .applicationProtocolConfig(new ApplicationProtocolConfig(
65 Protocol.ALPN,
66
67 SelectorFailureBehavior.NO_ADVERTISE,
68
69 SelectedListenerFailureBehavior.ACCEPT,
70 ApplicationProtocolNames.HTTP_2,
71 ApplicationProtocolNames.HTTP_1_1))
72 .build();
73 } else {
74 sslCtx = null;
75 }
76
77 EventLoopGroup group = new NioEventLoopGroup();
78 try {
79 ServerBootstrap b = new ServerBootstrap();
80 b.option(ChannelOption.SO_BACKLOG, 1024);
81 b.group(group)
82 .channel(NioServerSocketChannel.class)
83 .handler(new LoggingHandler(LogLevel.INFO))
84 .childHandler(new Http2ServerInitializer(sslCtx));
85
86 Channel ch = b.bind(PORT).sync().channel();
87
88 System.err.println("Open your HTTP/2-enabled web browser and navigate to " +
89 (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/');
90
91 ch.closeFuture().sync();
92 } finally {
93 group.shutdownGracefully();
94 }
95 }
96 }