zoukankan      html  css  js  c++  java
  • 使用Netty实现HttpServer

    package netty;
    
    import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
    import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
    import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
    import static io.netty.handler.codec.http.HttpResponseStatus.OK;
    import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
    import static org.jboss.netty.handler.codec.http.HttpHeaders.Values.KEEP_ALIVE;
    
    import com.alibaba.fastjson.JSON;
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.Channel;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelFutureListener;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelOption;
    import io.netty.channel.ChannelPipeline;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.SimpleChannelInboundHandler;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    import io.netty.handler.codec.http.DefaultFullHttpResponse;
    import io.netty.handler.codec.http.FullHttpRequest;
    import io.netty.handler.codec.http.FullHttpResponse;
    import io.netty.handler.codec.http.HttpHeaderValues;
    import io.netty.handler.codec.http.HttpObjectAggregator;
    import io.netty.handler.codec.http.HttpServerCodec;
    import io.netty.handler.codec.http.HttpServerExpectContinueHandler;
    import io.netty.handler.codec.http.HttpUtil;
    import io.netty.handler.ssl.SslContext;
    import io.netty.handler.ssl.SslContextBuilder;
    import io.netty.handler.ssl.SslHandler;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.nio.charset.StandardCharsets;
    import java.security.KeyStore;
    import javax.net.ssl.KeyManagerFactory;
    import lombok.Cleanup;
    import lombok.RequiredArgsConstructor;
    import lombok.SneakyThrows;
    
    /**
     * Test
     *
     * @author xfyou
     */
    public class Test {
    
      @SneakyThrows
      public static void main(String[] args) {
        HttpServer server = new HttpServer(8080);
        server.start();
      }
    
      @RequiredArgsConstructor
      private static class HttpServer {
    
        private final Integer port;
    
        @SneakyThrows
        public void start() {
          EventLoopGroup bossGroup = new NioEventLoopGroup(1);
          EventLoopGroup workerGroup = new NioEventLoopGroup(20);
          try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializerImpl());
            ChannelFuture future = serverBootstrap.bind(port).sync();
            System.out.println("Server started...");
            future.channel().closeFuture().sync();
          } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
          }
        }
    
      }
    
      private static final class ChannelInitializerImpl extends ChannelInitializer<Channel> {
    
        private final SslContext sslContext;
    
        @SneakyThrows
        public ChannelInitializerImpl() {
          sslContext = createSslContext();
        }
    
        @SneakyThrows
        private SslContext createSslContext() {
          String keyStoreFilePath = "/root/.ssl/test.pkcs12";
          String keyStorePassword = "passwd";
          KeyStore keyStore = KeyStore.getInstance("PKCS12");
          @Cleanup InputStream inputStream = new FileInputStream(keyStoreFilePath);
          keyStore.load(inputStream, keyStorePassword.toCharArray());
          KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
          keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
          return SslContextBuilder.forServer(keyManagerFactory).build();
        }
    
        @Override
        protected void initChannel(Channel ch) {
          ChannelPipeline cp = ch.pipeline();
          // support SSL/TLS
          cp.addLast(new SslHandler(sslContext.newEngine(ch.alloc())));
          // decode and encode
          cp.addLast(new HttpServerCodec());
          // handle message-body of POST
          cp.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
          cp.addLast(new HttpServerExpectContinueHandler());
          cp.addLast(new SimpleChannelInboundHandler<FullHttpRequest>() {
            @Override
            protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) {
              System.out.println(msg.content().toString(StandardCharsets.UTF_8));
              System.out.println(ch);
              String res = "I am OK";
              FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(JSON.toJSONString(res).getBytes(StandardCharsets.UTF_8)));
              response.headers().set(CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
              response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
              if (HttpUtil.isKeepAlive(msg)) {
                response.headers().set(CONNECTION, KEEP_ALIVE);
                ctx.writeAndFlush(response);
              } else {
                ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
              }
              ctx.flush();
            }
          });
        }
      }
    
    }
  • 相关阅读:
    使用Visual Studio给SharePoint列表添加Event Receiver
    使用客户端对象模型回写SharePoint列表
    思考:通过源码进行安装的前提是什么
    思考:学习一门语言真的是仅仅只有为了使用吗?或者说学习一个语言如果在工作中不使用,那么学习它还有什么好处和价值呢?
    思考:(使用下载工具比如yum,maven等)下载(库或者jar)到本地都需要设置源
    思考:代码块的大小是进行代码抽出一个方法或者进行重构或者是否在设计时设计为一个方法的衡量因素之一吗?
    思考:对源的包装是为了更好的隔离和在中间插入一些层?
    Spring Cloud和Spring Boot的认识
    如何对待基础知识:
    为什么总觉得事情应付不过来,总觉得事情需要花费很多时间?
  • 原文地址:https://www.cnblogs.com/frankyou/p/12144087.html
Copyright © 2011-2022 走看看