Netty实现HTTP服务

代码实现

前情提要

  1. 如果你想采取行动 FullHttpRequest 你需要 HttpObjectAggregator 在管道中,负责组装这些部件。
  2. 没有这个你会收到 HttpRequest, HttpContent, LastHttpContent表示HTTP消息部分的实例。每一个都需要处理,而 HTT请求标记新HTTP消息的开始,并 最后一个httpcontent结束了。
  • 服务端
package com.wyk.day02;

import com.wyk.day01.SeverHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;


/**
 * @program: NettyCode
 * @description:
 * @author: WYK
 * @create: 2021-08-30 21:29
 **/
public class SeverHttp {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline  pipeline= socketChannel.pipeline();
                            pipeline.addLast(new HttpServerCodec());//http编解码
                            pipeline.addLast("httpAggregator",new HttpObjectAggregator(512*1024)); // http 消息聚合器
                            pipeline.addLast(new SeverHandler1());
                        }
                    });
            ChannelFuture future = bootstrap.bind(8088).sync();
            future.addListener(future1 -> {
                if (future1.isSuccess()){
                    System.out.println("服务端准备就绪");
                }
            });
            future.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
            System.out.println("服务器结束");
        }
    }
}
  • 服务端Handler
package com.wyk.day02;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * @program: NettyCode
 * @description:
 * @author: WYK
 * @create: 2021-08-30 21:36
 **/
public class SeverHandler1 extends SimpleChannelInboundHandler<FullHttpRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest)
            throws Exception {
        System.out.println("收到请求");
        //获取请求uri
        String uri = fullHttpRequest.uri();
        String msg = "<html><head><title>test</title></head><body>你请求uri为:" + uri+"</body></html>";
        //ByteBuf buf = Unpooled.copiedBuffer("你好浏览器",CharsetUtil.UTF_8);
        //创建http响应
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK, Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));

        //设置头信息
        response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/html;charset=utf-8");
        //发送消息到浏览器
        channelHandlerContext.writeAndFlush(response);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值