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