netty学习笔记08 -Netty的Http服务

  • 实例要求
  1. 实例要求:使用IDEA 创建Netty项目
  2. Netty 服务器在 6668 端口监听,浏览器发出请求 "http://localhost:6668/ "
  3. 服务器可以回复消息给客户端 "Hello! 我是服务器 5 " , 并对特定请求资源进行过滤.
  4. 目的:Netty 可以做Http服务开发,并且理解Handler实例和客户端及其请求的关系.

服务器:

public class HttpNettyServer {

    public static void main(String[] args) throws InterruptedException {
        // 创建2个线程组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        // 创建引导启动项
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // 开始配置链式编程
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    // 配置处理器
                    .childHandler(new HttpServerInitializer());
            System.out.println("服务器已启动....");
            ChannelFuture channelFuture = serverBootstrap.bind(6668).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

处理器

public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        // 得到管道
        ChannelPipeline pipeline = socketChannel.pipeline();
        // 往管道添加编解码器
        pipeline.addLast("MyHttpServerCodec", new HttpServerCodec());
        // 添加一个自定义的处理器
        pipeline.addLast("MyHttpServerHandler", new HttpNettyServerHandler());
        System.out.println("ok。。。。");
    }
}
public class HttpNettyServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject msg) throws Exception {
        // 判断msg是不是httpRequest请求
        if (msg instanceof HttpRequest) {
            System.out.println("收到来自客户端:"+ channelHandlerContext.channel().remoteAddress()+"消息");
            HttpRequest request = (HttpRequest) msg;

            // 回复浏览器
            ByteBuf content = Unpooled.copiedBuffer("Hello,浏览器,我是服务器", CharsetUtil.UTF_8);
            // 构造一个http相应的httpResponse
            FullHttpResponse 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返回
            channelHandlerContext.writeAndFlush(response);
        }
    }
}
发布了83 篇原创文章 · 获赞 3 · 访问量 9842

猜你喜欢

转载自blog.csdn.net/fyj13925475957/article/details/104354695