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.netty5.example.http2.tiles;
18  
19  import io.netty5.bootstrap.ServerBootstrap;
20  import io.netty5.channel.Channel;
21  import io.netty5.channel.ChannelInitializer;
22  import io.netty5.channel.ChannelOption;
23  import io.netty5.channel.EventLoopGroup;
24  import io.netty5.channel.socket.SocketChannel;
25  import io.netty5.channel.socket.nio.NioServerSocketChannel;
26  import io.netty5.handler.codec.http.HttpObjectAggregator;
27  import io.netty5.handler.codec.http.HttpRequestDecoder;
28  import io.netty5.handler.codec.http.HttpResponseEncoder;
29  import io.netty5.handler.logging.LogLevel;
30  import io.netty5.handler.logging.LoggingHandler;
31  import io.netty5.util.concurrent.Future;
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 Future<Void> 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).asStage().get();
64          return ch.closeFuture();
65      }
66  }