第一个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}合二为一进行编解码
    /**
  • A combination of {@link HttpRequestDecoder} and {@link HttpResponseEncoder}
  • which enables easier server side HTTP implementation.
  • @see HttpClientCodec
    */

 

		

 	
 



猜你喜欢

转载自blog.csdn.net/qq_38393471/article/details/89381067