天天看點

第一個netty程式(使用netty進行http開發)

學習目的:了解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}合二為一進行編解碼