View Javadoc
1   /*
2    * Copyright 2015 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
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   * Demonstrates an http server using Netty to display a bunch of images, simulate
35   * latency and compare it against the http2 implementation.
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  }