Netty剖析之Http服务案例

前言

前面我们讲了Netty的线程模型,还有一些Netty的特性,以及使用Netty编写过一个Tcp服务案例,本次呢,我们将结合前面所学的知识,来编写一个Http服务案例

Http服务案例

需求:使用Netty编写一个Http服务端,可以让浏览器正常访问,并且服务端可以返回信息给浏览器。

服务端代码基本与前面的TCP服务一致,只是在pipeline管道里额外加入了处理http的编码、解码器(HttpServerCodec),自定义的handler不在继承ChannelInboundHandlerAdapter,而是继承SimpleChannelInboundHandler,详见如下代码:

public class HttpServer {
    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 ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // 获取管道对象
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            // 添加netty提供的处理http的编码、解码器
                            pipeline.addLast(new HttpServerCodec());
                            // 加入自定义的handler
                            pipeline.addLast(new HttpServerHandler());
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
        // 判断是不是Http请求
        if(httpObject instanceof HttpRequest){

            // 得到http请求
            HttpRequest httpRequest = (HttpRequest) httpObject;
            // 请求地址信息
            URI uri = new URI(httpRequest.uri());
            System.out.println("request url :" + uri.getPath());

            ByteBuf content = Unpooled.copiedBuffer("hello client", CharsetUtil.UTF_8);
            // 创建http响应对象
            DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            // 设置响应头
            httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plan");
            httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            channelHandlerContext.writeAndFlush(httpResponse);
        }
    }
}

浏览器访问测试:
在这里插入图片描述
可以看到,浏览器请求成功了,并且收到了服务端响应的信息。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值