1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.netty.example.http2.tiles;
18
19 import static io.netty.handler.codec.http2.Http2SecurityUtil.CIPHERS;
20 import io.netty.bootstrap.ServerBootstrap;
21 import io.netty.channel.Channel;
22 import io.netty.channel.ChannelFuture;
23 import io.netty.channel.ChannelInitializer;
24 import io.netty.channel.ChannelOption;
25 import io.netty.channel.EventLoopGroup;
26 import io.netty.channel.socket.SocketChannel;
27 import io.netty.channel.socket.nio.NioServerSocketChannel;
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.SslContext;
34 import io.netty.handler.ssl.SslContextBuilder;
35 import io.netty.handler.ssl.SupportedCipherSuiteFilter;
36 import io.netty.handler.ssl.util.SelfSignedCertificate;
37
38 import java.security.cert.CertificateException;
39
40 import javax.net.ssl.SSLException;
41
42
43
44
45
46
47 public class Http2Server {
48
49 public static final int PORT = Integer.parseInt(System.getProperty("http2-port", "8443"));
50
51 private final EventLoopGroup group;
52
53 public Http2Server(EventLoopGroup eventLoopGroup) {
54 group = eventLoopGroup;
55 }
56
57 public ChannelFuture start() throws Exception {
58 final SslContext sslCtx = configureTLS();
59 ServerBootstrap b = new ServerBootstrap();
60 b.option(ChannelOption.SO_BACKLOG, 1024);
61 b.group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
62 @Override
63 protected void initChannel(SocketChannel ch) throws Exception {
64 ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()), new Http2OrHttpHandler());
65 }
66 });
67
68 Channel ch = b.bind(PORT).sync().channel();
69 return ch.closeFuture();
70 }
71
72 private static SslContext configureTLS() throws CertificateException, SSLException {
73 SelfSignedCertificate ssc = new SelfSignedCertificate();
74 ApplicationProtocolConfig apn = new ApplicationProtocolConfig(
75 Protocol.ALPN,
76
77 SelectorFailureBehavior.NO_ADVERTISE,
78
79 SelectedListenerFailureBehavior.ACCEPT,
80 ApplicationProtocolNames.HTTP_2,
81 ApplicationProtocolNames.HTTP_1_1);
82
83 return SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey(), null)
84 .ciphers(CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
85 .applicationProtocolConfig(apn).build();
86 }
87 }