17.Netty-HttpServer编码实战

基础组件:3.Netty全局入口Bootstrap · 5.Netty的EventLoop · 6.Netty的ChannelPipeline · 7.Netty的ChannelHandler与Context

1. 启动类

public static void main(String[] args) throws InterruptedException {
    //主从线程池
    // 主接收客户端连接
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new HttpServerInitializer());

        //绑定端口,[同步]等待成功
        ChannelFuture channelFuture = bootstrap.bind(10086).sync();
        //监听关闭的Channel
        channelFuture.channel().closeFuture().sync();

    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

}

2. 处理器编写


/**
 - channel注册后,会执行里面初始化方法
 *
 - @author ldd */
 public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {


    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        //通过Channel获取管道
        ChannelPipeline pipeline = channel.pipeline();
        //通过管道 添加 Handler处理器 http的编解码处理器
        pipeline.addLast("HttpServerCodec", new HttpServerCodec());
        //自定义处理器
        //pipeline.addLast("HttpHandler", new HttpHandler());

    }
}

3. 自定义处理器


/**
 - 自定义助手类
 - SimpleChannelInboundHandler 对于请求来说,等于入站
 */
public class HttpHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        //数据可再次处理
        Channel channel = ctx.channel();
        //客户端远程地址
        System.out.println(channel.remoteAddress());
        // 缓冲区 ,读写数据通过
        ByteBuf byteBuf = Unpooled.copiedBuffer("hello netty", CharsetUtil.UTF_8);

        // 构建response
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK, byteBuf);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE);
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH,byteBuf.readableBytes());

        ctx.writeAndFlush(response);

    }
}