最近在看閃電俠的《Netty深刻剖析》,記錄總結。html
首先先看一個簡單的HelloWord:Server.java 和 ServerHandler.javajava
Server.java編程
EventLoopGroup bossGroup = new NioEventLoopGroup(1);// parent group EventLoopGroup workGroup = new NioEventLoopGroup();// child group try { ServerBootstrap serverBoot = new ServerBootstrap(); serverBoot.group(bossGroup,workGroup) .channel(NioServerSocketChannel.class)// 設置服務端Channel .childOption(ChannelOption.TCP_NODELAY,true)// 設置TCP的基本屬性 .childAttr(AttributeKey.newInstance("childAttr"),"childAttrValue") .handler(new ServerHandler())// 服務端啓動過程當中有什麼邏輯 .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { //ch.pipeline().addLast(); } }); ChannelFuture future = serverBoot.bind(8888).sync(); future.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workGroup.shutdownGracefully(); }
ServerHandler.javasocket
public class ServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { System.out.println("channelRegistered"); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("channelActive"); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { System.out.println("handlerAdded"); } }
啓動Server,運行結果以下:ide
Connected to the target VM, address: '127.0.0.1:2578', transport: 'socket' handlerAdded channelRegistered channelActive
把Socket編程中的幾個步驟和Netty中一一對應:oop
1.監聽端口 <-> NioEventLoop(NIO事件循環):具體是分別開兩個線程處理,spa
(1)Server某一端口監聽新用戶的鏈接;線程
(2)鏈接創建之後數據的讀寫。code
2.新鏈接 <-> Channel(NIO中是SocketChannel)server
3.接收數據 <-> ByteBuf(數據流接收載體)
4.業務邏輯 <-> ChannelHandler(每個處理過程) Pipeline
5.發送數據 <-> ByteBuf
1.NioEventLoop -> Thread(2個線程),分別負責,
(1)服務端接收客戶端鏈接;
(2)處理每一個鏈接的讀寫。
2.Channel -> Socket,通訊
3.ByteBuf - IO Bytes,封裝底層輸入輸出流
4.Pipeline - Logic Chain 業務邏輯鏈
5.ChannelHandler - Logic 邏輯處理塊
後面咱們將從Netty-服務端Channel的建立開始,分析Netty源碼。