Netty(二) 实现简单Http服务器

 --------使用Netty简单的实现Http服务器

Netty相关组件能够去看个人上一篇博客   Netty(一) 里面有介绍html

服务端:

/**
 * @Author Joker
 * @Date 2020/11/13
 * @since 1.8
 */
public class HttpServerDemo {
    public static void main(String[] args) {
        // 建立主从
        EventLoopGroup masterEventLoopGroup = new NioEventLoopGroup();
        EventLoopGroup slaveEventLoopGroup = new NioEventLoopGroup();

        // 建立服务启动类
        ServerBootstrap bootstrap = new ServerBootstrap();
        // 绑定主从模式
        bootstrap.group(masterEventLoopGroup, slaveEventLoopGroup);
        // 绑定通道
        bootstrap.channel(NioServerSocketChannel.class);

        bootstrap.childHandler(new ChannelInitializer() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                ChannelPipeline pipeline = channel.pipeline();
                // 添加Http编码器,该解码器会将字符串转成HttpRequest
                pipeline.addLast(new HttpServerCodec());
                // 将编码器HttpRequest转成FullHttpRequest对象
                pipeline.addLast(new HttpObjectAggregator(1024 * 1024));
                pipeline.addLast(new HttpChannelHandler());
            }
        });
        ChannelFuture bind = bootstrap.bind("127.0.0.1", 8888);
        try {
            bind.sync();
            System.out.println("服务启动成功");
            bind.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            masterEventLoopGroup.shutdownGracefully();
            slaveEventLoopGroup.shutdownGracefully();
        }
    }
}

 Http消息处理器

/**
 * @Author Joker
 * @Date 2020/11/14
 * @since 1.8
 */
public class HttpChannelHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception {
        String name = fullHttpRequest.method().name();
        System.out.println("请求方法: " + name);

        HttpHeaders headers = fullHttpRequest.headers();
        List<Map.Entry<String, String>> entries = headers.entries();
        for (Map.Entry<String, String> entry : entries) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }

        String con = fullHttpRequest.content().toString(Charset.defaultCharset());
        System.out.println("内容: " + con);

        // 相应页面,设置相应信息
        String respMsg = "<html>Hello World</html>";
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        response.headers().add("context-type", "text/html;charset=utf-8");
        response.content().writeBytes(respMsg.getBytes("UTF-8"));
        channelHandlerContext.writeAndFlush(response);
    }

运行服务端,能够经过网页访问地址

 咱们的消息处理器就会把咱们请求的相关信息打印出来...java

好啦,这就是一个使用Netty简单实现的Http服务器bootstrap