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 io.netty.bootstrap.ServerBootstrap;
20 import io.netty.channel.Channel;
21 import io.netty.channel.ChannelFuture;
22 import io.netty.channel.ChannelInitializer;
23 import io.netty.channel.ChannelOption;
24 import io.netty.channel.EventLoopGroup;
25 import io.netty.channel.socket.SocketChannel;
26 import io.netty.channel.socket.nio.NioServerSocketChannel;
27 import io.netty.handler.codec.http.HttpObjectAggregator;
28 import io.netty.handler.codec.http.HttpRequestDecoder;
29 import io.netty.handler.codec.http.HttpResponseEncoder;
30 import io.netty.handler.logging.LogLevel;
31 import io.netty.handler.logging.LoggingHandler;
32
33
34
35
36
37 public final class HttpServer {
38
39 public static final int PORT = Integer.parseInt(System.getProperty("http-port", "8080"));
40 private static final int MAX_CONTENT_LENGTH = 1024 * 100;
41
42 private final EventLoopGroup group;
43
44 public HttpServer(EventLoopGroup eventLoopGroup) {
45 group = eventLoopGroup;
46 }
47
48 public ChannelFuture start() throws Exception {
49 ServerBootstrap b = new ServerBootstrap();
50 b.option(ChannelOption.SO_BACKLOG, 1024);
51
52 b.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
53 .childHandler(new ChannelInitializer<SocketChannel>() {
54 @Override
55 protected void initChannel(SocketChannel ch) throws Exception {
56 ch.pipeline().addLast(new HttpRequestDecoder(),
57 new HttpResponseEncoder(),
58 new HttpObjectAggregator(MAX_CONTENT_LENGTH),
59 new Http1RequestHandler());
60 }
61 });
62
63 Channel ch = b.bind(PORT).sync().channel();
64 return ch.closeFuture();
65 }
66 }