01.netty执行流程简述

netty执行流程简述

TestServer.java

1package com.mzj.netty.ssy._01_simplehttp; 2 3import io.netty.bootstrap.ServerBootstrap; 4import io.netty.channel.ChannelFuture; 5import io.netty.channel.EventLoopGroup; 6import io.netty.channel.nio.NioEventLoopGroup; 7import io.netty.channel.socket.nio.NioServerSocketChannel; 8 9/** 10 * netty服务端程序流程 11 */ 12public class TestServer { 13 14 public static void main(String[] args) throws InterruptedException { 15 16 //1.创建boss与worker线程组(事件循环组) 17 EventLoopGroup boss = new NioEventLoopGroup(); 18 EventLoopGroup worker = new NioEventLoopGroup(); 19 //2.创建服务器启动辅助类,服务端是 ServerBootstrap 20 try { 21 ServerBootstrap serverBootstrap = new ServerBootstrap(); 22 //3.设置childHandler的初始化器 23 serverBootstrap.group(boss, worker).channel(NioServerSocketChannel.class). 24 childHandler(new TestServerInitiallzer()); 25 26 //5.绑定服务器端口并启动服务器,同步等待服务器启动完毕 27 ChannelFuture channelFuture = serverBootstrap.bind(8899).sync(); 28 //6.阻塞启动线程,并同步等待服务器关闭,因为如果不阻塞启动线程,则会在finally块中执行优雅关闭,导致服务器也会被关闭了 29 channelFuture.channel().closeFuture().sync(); 30 } finally { 31 boss.shutdownGracefully(); 32 worker.shutdownGracefully(); 33 } 34 35 } 36} 37 38
  1. 创建boss与worker事件循环线程组
  2. 创建服务器启动辅助类,服务端是 ServerBootstrap,客户端是Bootstrap
  3. 配置bootstrap:绑定线程组、设置channel、设置handler、设置childHandler(一般使用childHandler的初始化器-->handler的方式配置childHandler)
  4. 在初始化器的initChannel方法中添加各种handler,包括netty内置的+我们自定义的处理业务逻辑的handler
  5. 实现自定义的handler:通过实现netty在不同抽象父类handler中定义的回调方法,如下图,之后当特定的事件发生时,特定的回调方法被调用,根据事件处理对应的业务逻辑
  6. 绑定服务器端口并启动服务器,同步等待服务器启动完毕
  7. 阻塞启动线程,并同步等待服务器关闭,因为如果不阻塞启动线程,则会在finally块中执行优雅关闭,导致服务器也会被关闭了

TestServerInitiallzer.java

1package com.mzj.netty.ssy._01_simplehttp; 2 3import io.netty.channel.ChannelInitializer; 4import io.netty.channel.ChannelPipeline; 5import io.netty.channel.socket.SocketChannel; 6import io.netty.handler.codec.http.HttpServerCodec; 7 8public class TestServerInitiallzer extends ChannelInitializer<SocketChannel> { 9 @Override 10 protected void initChannel(SocketChannel ch) throws Exception { 11 //4.在初始化器的initChannel方法中添加各种handler,包括处理业务逻辑的自定义handler 12 ChannelPipeline pipeline = ch.pipeline(); 13 pipeline.addLast("httpServerCodec",new HttpServerCodec()); 14 pipeline.addLast("testHttpServerHandler",new TestHttpServerHandler()); 15 16 } 17} 18 19

 

1 2TestHttpServerHandler.java 3
1package com.mzj.netty.ssy._01_simplehttp; 2 3import io.netty.buffer.ByteBuf; 4import io.netty.buffer.Unpooled; 5import io.netty.channel.ChannelHandlerContext; 6import io.netty.channel.SimpleChannelInboundHandler; 7import io.netty.handler.codec.http.*; 8import io.netty.util.CharsetUtil; 9 10import java.net.URI; 11 12public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> { 13 14 @Override 15 protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { 16 17 System.out.println(msg.getClass()); 18 System.out.println(ctx.channel().remoteAddress()); 19 20 if(msg instanceof HttpRequest){ 21 HttpRequest httpRequest = (HttpRequest) msg; 22 23 System.out.println("请求方法名...:" + httpRequest.method().name()); 24 //过滤chrome等浏览器请求网站图标的请求 25 URI uri = new URI(httpRequest.uri()); 26 if("/favicon.ico".equals(uri.getPath())){ 27 System.out.println("请求favicon.ico"); 28 return; 29 } 30 31 System.out.println("channelRead0执行了..."); 32 //模拟响应结果数据 33 ByteBuf result = Unpooled.copiedBuffer("mazhongjia", CharsetUtil.UTF_8); 34 35 //FullHttpResponse是netty提供的封装http响应的类 36 FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,result); 37 38 //设置http返回对象头信息 39 response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain"); 40 response.headers().set(HttpHeaderNames.CONTENT_LENGTH,result.readableBytes()); 41 42 //返回response 43 ctx.writeAndFlush(response); 44 //模拟http请求/响应后,服务的关闭客户端连接 45 //省略:判断http1.1或者1.0版本 46 ctx.channel().close(); 47 } 48 } 49 50 /** 51 * 客户端与服务端建立好连接时的回调函数 52 * @param ctx 53 * @throws Exception 54 */ 55 @Override 56 public void handlerAdded(ChannelHandlerContext ctx) throws Exception { 57 System.out.println("handlerAdded....."); 58 super.handlerAdded(ctx); 59 } 60 61 @Override 62 public void channelRegistered(ChannelHandlerContext ctx) throws Exception { 63 System.out.println("channelRegistered....."); 64 super.channelRegistered(ctx); 65 } 66 67 @Override 68 public void channelActive(ChannelHandlerContext ctx) throws Exception { 69 System.out.println("channelActive....."); 70 super.channelActive(ctx); 71 } 72 73 @Override 74 public void channelInactive(ChannelHandlerContext ctx) throws Exception { 75 System.out.println("channelInactive....."); 76 super.channelInactive(ctx); 77 } 78 79 @Override 80 public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { 81 System.out.println("channelUnregistered....."); 82 super.channelUnregistered(ctx); 83 } 84} 85 86

完整代码:https://github.com/mazhongjia/nettyssynetty02/tree/master/src/main/java/com/mzj/netty/ssy/_01_simplehttp

或者https://gitee.com/mazhongjia/netty-ssy-netty/tree/master/src/main/java/com/mzj/netty/ssy/_01_simplehttp

代码交流 2021