第一个netty程序(使用netty进行http开发)

本文深入解析了Netty服务器端的基本构建流程,包括事件循环组的使用、ServerBootstrap的配置、子处理器的定义,以及如何处理客户端请求并发送响应。通过示例代码展示了Netty在构建高性能网络应用方面的强大能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习目的:了解netty服务器端的基本构建过程

public class  TestServer {


    public static void main(String[] args) throws InterruptedException {
        //事件循环组         两个死循环
        EventLoopGroup bossGroup =new NioEventLoopGroup();      //不断接受客户端连接

        EventLoopGroup workerGroup=new NioEventLoopGroup();     //接受客户端连接后 进行处理
            try {


                ServerBootstrap serverBootstrap=new ServerBootstrap();
                serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).
                        childHandler(new TestServerInitializer());  //定义子处理器

                ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();

                channelFuture.channel().closeFuture().sync();
            }finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
    }
}
public class TestServerInitializer  extends ChannelInitializer<SocketChannel> {


    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        pipeline.addLast("httpServerCodec",new HttpServerCodec());

        pipeline.addLast("testHttpServerHandler",new TestHttpServerHandler() );
    }
}
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    //读取客户端请求,并且发送客户端响应
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpRequest) {
            ByteBuf content = Unpooled.copiedBuffer("Hello,world", CharsetUtil.UTF_8);
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);

            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            ctx.writeAndFlush(response);
        }
    }
}
  1. SimpleChannelInboundHandler 对进来的请求的处理类
    方法
 @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        System.out.println("channel active");
        super.channelActive(ctx);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {

        System.out.println("channel register");
        super.channelRegistered(ctx);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handler added");
        super.handlerAdded(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        System.out.println("channel inactive");
        super.channelInactive(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelUnregistered");

        super.channelUnregistered(ctx);
    }

客户端发送请求后上面的方法执行顺序如下:
handler added
channel register
channel active
channel Read0
channel inactive
channelUnregistered

2.在protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception方法中,打印 ctx.class 得到
class io.netty.handler.codec.http.DefaultHttpRequest
class io.netty.handler.codec.http.LastHttpContent$1

  • 下面再来看看 HttpServerCodec类
    他是一个final的类作用是将{@link HttpRequestDecoder} and {@link HttpResponseEncoder}合二为一进行编解码
    /**
  • A combination of {@link HttpRequestDecoder} and {@link HttpResponseEncoder}
  • which enables easier server side HTTP implementation.
  • @see HttpClientCodec
    */

 

		

 	
 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值