1. NioEventLoopGroup boss = new NioEventLoopGroup();
    2. NioEventLoopGroup worker = new NioEventLoopGroup();
    3. try {
    4. ServerBootstrap serverBootstrap = new ServerBootstrap();
    5. serverBootstrap.channel(NioServerSocketChannel.class);
    6. serverBootstrap.group(boss, worker);
    7. serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
    8. @Override
    9. protected void initChannel(SocketChannel ch) throws Exception {
    10. ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
    11. ch.pipeline().addLast(new HttpServerCodec());
    12. ch.pipeline().addLast(new SimpleChannelInboundHandler<HttpRequest>() {
    13. @Override
    14. protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
    15. // 获取请求
    16. log.debug(msg.uri());
    17. // 返回响应
    18. DefaultFullHttpResponse response =
    19. new DefaultFullHttpResponse(msg.protocolVersion(), HttpResponseStatus.OK);
    20. byte[] bytes = "<h1>Hello, world!</h1>".getBytes();
    21. response.headers().setInt(CONTENT_LENGTH, bytes.length);
    22. response.content().writeBytes(bytes);
    23. // 写回响应
    24. ctx.writeAndFlush(response);
    25. }
    26. });
    27. /*ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
    28. @Override
    29. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    30. log.debug("{}", msg.getClass());
    31. if (msg instanceof HttpRequest) { // 请求行,请求头
    32. } else if (msg instanceof HttpContent) { //请求体
    33. }
    34. }
    35. });*/
    36. }
    37. });
    38. ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
    39. channelFuture.channel().closeFuture().sync();
    40. } catch (InterruptedException e) {
    41. log.error("server error", e);
    42. } finally {
    43. boss.shutdownGracefully();
    44. worker.shutdownGracefully();
    45. }