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