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