Netty回调与Channel执行流程分析

在上一篇的基础上修改代码

1、TestHttpServerHandle  类

package com.example.firstexample;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

public class TestHttpServerHandle  extends SimpleChannelInboundHandler<HttpObject>{

    //读取客户端发送过来的请求,并且向客户端返回响应
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {

        CommonUtil.println(httpObject.getClass());
        CommonUtil.println(channelHandlerContext.channel().remoteAddress());
        if(httpObject instanceof  HttpRequest){
            HttpRequest httpRequest = (HttpRequest) httpObject;

            CommonUtil.println("请求方法名:" + httpRequest.method().name() + ",uri:" + httpRequest.uri());

            URI uri = new URI(httpRequest.uri());
            if("/favicon.ico".equals(uri.getPath())){
                CommonUtil.println("请求favicon.ico");
                return;
            }

            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());
            //写回客户端
            channelHandlerContext.writeAndFlush(response);
            //channelHandlerContext.close();
        }

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        CommonUtil.println("channel Active");
        super.channelActive(ctx);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        CommonUtil.println("channel Registered");
        super.channelRegistered(ctx);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        CommonUtil.println("channel Added");
        super.handlerAdded(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        CommonUtil.println("channel Inactive");
        super.channelInactive(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        CommonUtil.println("channel Unregistered");
        super.channelUnregistered(ctx);
    }
}

  

2、增加公共类CommonUtil 

public class CommonUtil {
    public static  void println(String msg){
        System.out.println(String.format("[thread-%s] %s",Thread.currentThread().getId(), msg));
    }

    public static  void println(Object msg){
        println(msg.toString());
    }
}

  

3、运行结果

使用postman调用

控制台打印如下图

猜你喜欢

转载自www.cnblogs.com/linlf03/p/11295000.html