netty004之Handler的生命周期

本文详细解析了一个基于Netty的简单HTTP服务器处理流程,包括从客户端请求的接收、解析到响应的生成与发送全过程。文章通过具体代码示例,展示了如何使用Netty的ChannelInboundHandler来实现HTTP请求的读取和响应的构造,同时涵盖了Netty中关键事件的触发与处理,如handlerAdded、channelRegistered等。
摘要由CSDN通过智能技术生成

一、代码

/**
 * http 响应
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    /**
     * 读取客户端请求,并给客户端响应的方法
     *
     * @param channelHandlerContext
     * @param httpObject
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
        if (httpObject instanceof HttpRequest) {
            HttpRequest httpRequest = (HttpRequest)httpObject;
            System.out.println("请求方法名:" + httpRequest.method().name());
            URI uri = new URI(httpRequest.uri());
            if("/favicon.ico".equals(uri.getPath())){
                System.out.println("请求favicon.ico");
                return;
            }
            // 响应内容
            String content2 = "Hello World! \t" + Thread.currentThread().getName() + "\r\n";
            ByteBuf content = Unpooled.copiedBuffer(content2, 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());
            channelHandlerContext.writeAndFlush(response);

        }
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //启动时只要程序员自己加上handler就会调用
        System.out.println("handlerAdded##################111111###################");
    }

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

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelRegistered################222222####################################");
        ctx.fireChannelRegistered();
    }

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

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelActive  ##################333333##################################");
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelInactive();
        System.out.println("channelInactive####################################################");
    }


    /**
     * 有此方法channelRead0就不执行了
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("channelRead#####################444444###############################");

        System.out.println(msg.getClass());
        System.out.println(  ctx.channel().remoteAddress());
        if (msg instanceof HttpRequest) {
            HttpRequest httpRequest = (HttpRequest)msg;
            System.out.println("请求方法名:" + httpRequest.method().name());
            URI uri = new URI(httpRequest.uri());
            if("/favicon.ico".equals(uri.getPath())){
                System.out.println("请求favicon.ico");
                return;
            }
            // 响应内容
            String content2 = "Hello World2! \t" + Thread.currentThread().getName() + "\r\n";
            ByteBuf content = Unpooled.copiedBuffer(content2, 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);

        }
        ctx.fireChannelRead(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelReadComplete();
        System.out.println("channelReadComplete####################5555555#############");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        ctx.fireUserEventTriggered(evt);
        System.out.println("userEventTriggered####################################################");
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelWritabilityChanged();
        System.out.println("channelWritabilityChanged####################################################");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.fireExceptionCaught(cause);
        System.out.println("userEventTriggered ####################################################");
    }
}

 

控制台打印结果:

handlerAdded##################111111###################
channelRegistered################222222####################################
channelActive  ##################333333##################################
channelRead#####################444444###############################
请求方法名:POST
22:49:26.182 [nioEventLoopGroup-3-4] DEBUG io.netty.channel.DefaultChannelPipeline - Discarded inbound message DefaultHttpRequest(decodeResult: success, version: HTTP/1.1)
POST / HTTP/1.1
User-Agent: curl/7.29.0
Host: 192.168.1.6:8888
Accept: */* that reached at the tail of the pipeline. Please check your pipeline configuration.
22:49:26.182 [nioEventLoopGroup-3-4] DEBUG io.netty.channel.DefaultChannelPipeline - Discarded message pipeline : [httpServerCodec, myTestHttpServerHandler, DefaultChannelPipeline$TailContext#0]. Channel : [id: 0x01175b58, L:/192.168.1.6:8888 - R:/192.168.1.9:41998].
channelRead#####################444444###############################
22:49:26.182 [nioEventLoopGroup-3-4] DEBUG io.netty.channel.DefaultChannelPipeline - Discarded inbound message EmptyLastHttpContent that reached at the tail of the pipeline. Please check your pipeline configuration.
22:49:26.182 [nioEventLoopGroup-3-4] DEBUG io.netty.channel.DefaultChannelPipeline - Discarded message pipeline : [httpServerCodec, myTestHttpServerHandler, DefaultChannelPipeline$TailContext#0]. Channel : [id: 0x01175b58, L:/192.168.1.6:8888 - R:/192.168.1.9:41998].
channelReadComplete####################5555555#############
channelReadComplete####################5555555#############
channelInactive####################################################
channelUnregistered####################################################
handlerRemoved####################################################

 

handlerAdded##################111111###################
channelRegistered################222222####################################
channelActive  ##################333333##################################
channelRead#####################444444###############################
请求方法名:POST
22:50:18.430 [nioEventLoopGroup-3-5] DEBUG io.netty.channel.DefaultChannelPipeline - Discarded inbound message DefaultHttpRequest(decodeResult: success, version: HTTP/1.1)
POST / HTTP/1.1
User-Agent: curl/7.29.0
Host: 192.168.1.6:8888
Accept: */* that reached at the tail of the pipeline. Please check your pipeline configuration.
22:50:18.430 [nioEventLoopGroup-3-5] DEBUG io.netty.channel.DefaultChannelPipeline - Discarded message pipeline : [httpServerCodec, myTestHttpServerHandler, DefaultChannelPipeline$TailContext#0]. Channel : [id: 0xcb21e6ba, L:/192.168.1.6:8888 - R:/192.168.1.9:41999].
channelRead#####################444444###############################
22:50:18.430 [nioEventLoopGroup-3-5] DEBUG io.netty.channel.DefaultChannelPipeline - Discarded inbound message EmptyLastHttpContent that reached at the tail of the pipeline. Please check your pipeline configuration.
22:50:18.430 [nioEventLoopGroup-3-5] DEBUG io.netty.channel.DefaultChannelPipeline - Discarded message pipeline : [httpServerCodec, myTestHttpServerHandler, DefaultChannelPipeline$TailContext#0]. Channel : [id: 0xcb21e6ba, L:/192.168.1.6:8888 - R:/192.168.1.9:41999].
channelReadComplete####################5555555#############
channelReadComplete####################5555555#############
channelInactive####################################################
channelUnregistered####################################################
handlerRemoved####################################################

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值