HTTP服务案例

案例要求:使用IDEA创建Netty项目

(1)Netty 服务在6688 端口监听,浏览器发出请求 "http://localhost:6688/";

(2)服务器可以回复消息给客户端 "Hello,我是服务器!",并对特定请求资源进行过滤;

(3)目的:Netty 可以做Http 服务开发,并且理解 Handler 实例和客户端及其请求的关系;

服务器端代码:

public class TestServer {
    public static void main(String[] args) throws Exception {

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new TestServerInitializer())
;

            ChannelFuture channelFuture = serverBootstrap.bind(6688).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());

        System.out.println("ok~~~~");
    }
}

自定义Handler对象:

/*
说明
1. SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter 的子类
2. HttpObject 客户端和服务器端相互通讯的数据被封装成 HttpObject
 */

public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject{

    //channelRead0 读取客户端数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        System.out.println("对应的channel=" + ctx.channel() + ",pipeline=" + ctx.pipeline()
                + ",通过pipeline获取channel" + ctx.pipeline().channel());

        System.out.println("当前ctx的handler=" + ctx.handler());


        //判断 msg 是不是 httpRequest请求
        if (msg instanceof HttpRequest) {

            System.out.println("ctx 类型 = " + ctx.getClass());
            System.out.println("pipeline hashcode = " + ctx.pipeline().hashCode()
                    + " TestHttpServerHandler hash =" + this.hashCode());


            System.out.println("msg 类型=" + msg.getClass());
            System.out.println("客户端地址" + ctx.channel().remoteAddress());

            //1.过滤资源
            HttpRequest httpRequest = (HttpRequest) msg;
            //获取uri, 过滤指定的资源
            URI uri = new URI(httpRequest.uri());
            if("/favicon.ico".equals(uri.getPath())) {
                System.out.println("请求了 favicon.ico, 不做响应");
                return;
            }


            //2.回复信息给浏览器 [http协议]
            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());


            //3.将构建好的 response 返回
            ctx.writeAndFlush(response);
        }
    }
}

测试结果:

posted on 2022-04-05 19:09  格物致知_Tony  阅读(89)  评论(0)    收藏  举报