netty构建简单的http服务器

初学netty 原理后面再弄 ,首先还得熟悉整体流程以及代码的熟练度

1.程序入口

public class main {
    public static void main(String[] args) throws Exception {
        //boss线程
        EventLoopGroup boss = new NioEventLoopGroup();
        //worker线程
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            //新建一个可以快速启动服务对象
            ServerBootstrap server = new ServerBootstrap();
            //指定boss worker线程 
            server.group(boss, worker).channel(NioServerSocketChannel.class)
                    .childHandler(new MyServerInitializer());
            //绑定端口号
            ChannelFuture future = server.bind(8080).sync();
            future.channel().closeFuture().sync();
        } finally {
            //优雅的关闭两类线程
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }
}

2.构建自己的handler初始化

public class MyServerInitializer extends ChannelInitializer {

    @Override
    protected void initChannel(Channel channel) throws Exception {
        //得到管道
        ChannelPipeline pipeline = channel.pipeline();
        //末尾添加http编码器和解码器(HttpServerCodec是同时拥有解码编码的功能)
        pipeline.addLast(new HttpServerCodec());
        //添加自己的handler
        pipeline.addLast(new MyServerHandler());

    }
}

3.创建自己的handler

class MyServerHandler extends SimpleChannelInboundHandler<HttpRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpRequest request) throws Exception {
        ByteBuf content = Unpooled.copiedBuffer("测试", CharsetUtil.UTF_8);
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=UTF-8");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
        ctx.writeAndFlush(response);
    }
}

4.测试
在浏览器中直接敲http://localhost:8080
得到结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值