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