美文网首页
HTTP服务实例

HTTP服务实例

作者: Cook1fan | 来源:发表于2021-04-17 16:43 被阅读0次
    image.png
    public class TestServer {
        public static void main(String[] args) throws InterruptedException {
            EventLoopGroup bossGroup = new NioEventLoopGroup(1);
            EventLoopGroup workerGroup = new NioEventLoopGroup(8);
            try {
                ServerBootstrap serverBootstrap = new ServerBootstrap();
                serverBootstrap.group(bossGroup, workerGroup) // 设置两个线程组
                        .channel(NioServerSocketChannel.class) // 设置 NioSctpServerChannel 作为服务器的通道实现
                        .childHandler(new TestServerInitializer()); // 给我们的 workGroup 的 EventLoop 对应的管道设置处理器
                ChannelFuture channelFuture = serverBootstrap.bind(7100).sync();
                channelFuture.channel().closeFuture().sync();
            } finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }
    }
    
    public class TestServerInitializer extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            // 向管道加入处理器
            // 得到管道
            ChannelPipeline pipeline = ch.pipeline();
            // 加入一个 netty 提供的 httpServerCodec codec - [coder - decoder]
            // HttpServerCodec 说明
            // 1. HttpServerCodec 是 netty 提供的处理 http 的 编解码器
            pipeline.addLast("MyHttpServerCodec", new HttpServerCodec());
            // 2. 增加一个自定义的 handler
            pipeline.addLast("MyTestHttpServerHandler", new TestHttpServerHandler());
        }
    }
    
    /**
     * 1. SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter 子类
     * 2. HttpObject 客户端和服务器端相互通讯的数据被封装成 HttpObject
     */
    public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
        // 读取客户端数据
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
            // 判断 msg 是不是 httpRequest 请求
            if (msg instanceof HttpRequest) {
                System.out.println("pipeline hashcode:" + ctx.pipeline().hashCode());
                System.out.println("TestHttpServerHandler hashcode:" + this.hashCode());
                System.out.println("msg 类型 = " + msg.getClass());
                System.out.println("客户端地址:" + ctx.channel().remoteAddress());
                // 获取到
                HttpRequest httpRequest = (HttpRequest) msg;
                // 获取 uri
                URI uri = new URI(httpRequest.uri());
                if ("/favicon.ico".equals(uri.getPath())) {
                    System.out.println("请求了 favicon.ico, 不做响应");
                    return;
                }
                // 回复信息给浏览器 [http 协议]
                ByteBuf content = Unpooled.copiedBuffer("hello, 我是服务器", CharsetUtil.UTF_8);
                // 构造一个 http 的响应,即 httpResponse
                DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
                response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
                response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
                // 将构建好的 response 返回
                ctx.writeAndFlush(response);
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:HTTP服务实例

          本文链接:https://www.haomeiwen.com/subject/eezklltx.html