Netty源码:从一个简单Demo开始

最近在看闪电侠的《Netty深刻剖析》,记录总结。html

一.Netty简单示例

    首先先看一个简单的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

 

二.Netty是对Socket的抽象

    把Socket编程中的几个步骤和Netty中一一对应:oop

    1.监听端口 <-> NioEventLoop(NIO事件循环):具体是分别开两个线程处理,spa

        (1)Server某一端口监听新用户的链接;线程

        (2)链接创建之后数据的读写。code

    2.新链接 <-> Channel(NIO中是SocketChannel)server

    3.接收数据 <-> ByteBuf(数据流接收载体)

    4.业务逻辑 <-> ChannelHandler(每个处理过程) Pipeline

    5.发送数据 <-> ByteBuf

   

三.Netty中的基本组件

    1.NioEventLoop -> Thread(2个线程),分别负责,

        (1)服务端接收客户端链接;

        (2)处理每一个链接的读写。

    2.Channel -> Socket,通讯

    3.ByteBuf - IO Bytes,封装底层输入输出流

    4.Pipeline - Logic Chain 业务逻辑链

    5.ChannelHandler - Logic 逻辑处理块

 

    后面咱们将从Netty-服务端Channel的建立开始,分析Netty源码。

相关文章
相关标签/搜索