Netty4启动ServerBootStrap源码分析

Netty 4源码解析:服务端启动 Netty 4源码解析:服务端启动1.基础知识1.1 Netty 4示例因为Netty 5还处于测试版,所以选择了目前比较稳定的Netty 4作为学习对象。而且5.0的变化也不像4.0这么大,好多网上的例子都已经过时了。 <dependency> <groupId>io.netty</groupId> <artifactId>netty- 阅读详情

首记:
来分析下Netty4中的核心NIO模型的启动过程, 如何 bind -> accept -> process -> …. 这些过程,在分析之前,先来熟悉下jdk中原生的NIO模型,
因为Netty中的NIO是基于此上面进行封装的。

一,java nio 模型

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;


class NioServer implements Runnable {

    private static final int DEFAULT_SEND_BUF_SIZE = 65535;
    private static final int DEFAULT_RECV_BUF_SIZE = 65535;
    private static final int DEFAULT_READ_TIMEOUT = 30000;
    private static final int DEFAULT_BACKLOG = 1024;

    private String host;
    private int port;

    private int sendBufSize;
    private int recvBufSize;

    //ms
    private int readTimeout;

    private ServerSocketChannel serverSocketChannel;

    private Selector selector;

    //server 正在启动
    private AtomicBoolean isStartingUp = new AtomicBoolean(false);

    //server 运行中
    private volatile boolean isRunning = false;

    //server 正在关闭
    private AtomicBoolean isShutdownIng = new AtomicBoolean(false);

    //server 关闭完成
    private volatile boolean isShutdownComplete = false;

    private InetSocketAddress serverLocalAddress;


    public NioServer(int port) {
        this(null, port);
    }

    public NioServer(String host, int port) {
        this(host, port, DEFAULT_SEND_BUF_SIZE, DEFAULT_RECV_BUF_SIZE, DEFAULT_READ_TIMEOUT);
    }

    public NioServer(String host, int port, int sendBufSize, int recvBufSize, int readTimeout) {
        this.host = host;
        if (port < 0) {
            throw new IllegalArgumentException("port must be positive");
        }
        this.port = port;
        this.sendBufSize = sendBufSize > 0 ? sendBufSize : DEFAULT_SEND_BUF_SIZE;
        this.recvBufSize = recvBufSize > 0 ? recvBufSize : DEFAULT_RECV_BUF_SIZE;
        this.readTimeout = readTimeout > 0 ? readTimeout : DEFAULT_READ_TIMEOUT;

    }


    private void initServerSocket() throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        serverSocketChannel.socket().setSoTimeout(this.readTimeout);
        serverSocketChannel.socket().setReceiveBufferSize(this.recvBufSize);
        serverSocketChannel.socket().setReuseAddress(true);

        InetSocketAddress address;
        if (host != null) {
            address = new InetSocketAddress(host, port);
        } else {
            address = new InetSocketAddress(port);
        }

        serverSocketChannel.bind(address, DEFAULT_BACKLOG);
        this.serverLocalAddress = (InetSocketAddress) serverSocketChannel.getLocalAddress();
        System.out.printf("********************  Bind Local Address [%s:%d]  ************************\n",
                this.serverLocalAddress.getHostName(), this.serverLocalAddress.getPort());

        this.serverSocketChannel = serverSocketChannel;
    }

    private void initSelector() throws IOException {
        this.selector = Selector.open();
    }


    private void init() throws IOException {
        if (!isStartingUp.compareAndSet(false, true)) {
            return;
        }

        if (isRunning) {
            return;
        }

        initServerSocket();
        initSelector();

        this.serverSocketChannel.configureBlocking(false);
        this.serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT );

        this.isRunning = true;
        this.isStartingUp.compareAndSet(true, false);
    }


    @Override
    public void run() {
        try {
            init();
        } catch (IOException e) {
            e.printStackTrace();
        }

        while (this.selector.isOpen()) {

            int select = 0;
            try {
                select = this.selector.select(500);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (select > 0 && isRunning) {
                Set<SelectionKey> selectionKeys = this.selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                while (it.hasNext()) {
                    SelectionKey key = it.next();
                    it.remove();

                    if (!key.isValid()) {
                        continue;
                    }

                    //accept
                    if (key.isAcceptable()) {
                        try {
                            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                            SocketChannel socketChannel = serverSocketChannel.accept();

                            socketChannel.socket().setSendBufferSize(this.sendBufSize);
                            socketChannel.socket().setSoTimeout(this.readTimeout);
                            socketChannel.socket().setReceiveBufferSize(this.recvBufSize);
                            socketChannel.socket().setKeepAlive(true);
                            socketChannel.socket().setReuseAddress(true);
                            socketChannel.socket().setTcpNoDelay(true);
                            socketChannel.configureBlocking(false);


                            InetSocketAddress local = (InetSocketAddress) socketChannel.getLocalAddress();
                            InetSocketAddress remote = (InetSocketAddress) socketChannel.getRemoteAddress();

                            System.out.printf("Accept Channel : [%s:%d] -> [%s:%d]\n",
                                    remote.getHostName(), remote.getPort(),
                                    local.getHostName(), local.getPort());

                            socketChannel.register(this.selector, SelectionKey.OP_READ);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    if (key.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        if (socketChannel.isOpen()) {
                            try {
                                ByteBuffer buffer = ByteBuffer.allocate(1024);
                                int len = socketChannel.read(buffer);
                                if (len > 0) {
                                    System.out.println(new String(buffer.array(), 0, len));

                                    String httpResponse = "HTTP/1.1 200 OK\r\n" +
                                            "Content-Length: 38\r\n" +
                                            "Content-Type: text/html\r\n" +
                                            "\r\n" +
                                            "<html><body>Hello World!</body></html>";
                                    socketChannel.write(ByteBuffer.wrap(httpResponse.getBytes()));
                                } else {
                                    key.interestOps(key.interestOps() &~ SelectionKey.OP_READ);
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                                try {
                                    socketChannel.close();
                                    key.cancel();
                                } catch (IOException e1) {
                                    e1.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    public void shutdown() {
        if (!this.isShutdownIng.compareAndSet(false, true)) {
            return;
        }
        if (this.isShutdownComplete) {
            return;
        }

        isRunning = false;

        try {
            this.serverSocketChannel.socket().close();
            this.serverSocketChannel.close();

            this.selector.wakeup();
            this.selector.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Fail to shutdown server ... ");
            throw new RuntimeException(e);
        }


        this.isShutdownComplete = true;
        this.isShutdownIng.compareAndSet(true, false);

        System.out.printf("**************** shutdown server[%s:%d] successfully **************\n",
                this.serverLocalAddress.getHostName(), this.serverLocalAddress.getPort());
    }

}




public class NioDemo {


    public static void main(String[] args) throws InterruptedException {

        NioServer server = new NioServer(8888);
        new Thread(server).start();


        Thread.sleep(100000);
        server.shutdown();
    }
}

上面实现一个简单的Nio socket server, 用浏览器可访问 http://localhost:8888

二,Netty ServerBootstrap 源码分析

先用netty来简单实现上面例子的功能:

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;

public class NettyServerDemo {


    public static void main(String[] args) {

        EventLoopGroup accept = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup(4);

        ServerBootstrap b = new ServerBootstrap();

        b.group(accept, worker)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_RCVBUF, 65535)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                                int len = msg.readableBytes();
                                byte[] bytes = new byte[len];
                                msg.getBytes(0, bytes);
                                System.out.println(new String(bytes));
                                String httpResponse = "HTTP/1.1 200 OK\r\n" +
                                        "Content-Length: 38\r\n" +
                                        "Content-Type: text/html\r\n" +
                                        "\r\n" +
                                        "<html><body>Hello World!</body></html>";

                                ByteBuf buffer = ctx.alloc().buffer();
                                buffer.writeBytes(httpResponse.getBytes("UTF8"));
                                ctx.writeAndFlush(buffer);
                            }
                        });
                    }
                })
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.SO_REUSEADDR, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.SO_RCVBUF, 65535)
                .childOption(ChannelOption.SO_SNDBUF, 65535)
                .localAddress(8888);


        ChannelFuture channelFuture = b.bind().awaitUninterruptibly();

        if (channelFuture.isSuccess()) {
            Channel channel = channelFuture.channel();
            InetSocketAddress address = (InetSocketAddress) channel.localAddress();
            System.out.printf("********* BIND LOCAL ADDRESS [%s:%d] SUCCESSFULLY ********\n",
                    address.getHostName(), address.getPort());
        }

    }
}

以上面例子说起, 开始初始化了两个线程组 accept, worker

EventLoopGroup accept = new NioEventLoopGroup(1);
EventLoopGroup worker = new NioEventLoopGroup(4);

用于 Nio server 的io事件处理线程, 顾名思义,accept 用于ServerSocketChannel accept io事件 ,worker 用于SocketChannel read,write读写io事件,其中线程组的每个线程都对应了唯一一个Selector,用于io事件,也就是线程(其实就是NioEventLoop 与 Selector 一一对应),等会儿可以简单的来看看,因为这不是这篇文章的重点,以后可以专门写篇文章来剖析一下Netty中有关于nio线程对象的封装。

现在来简单的看下NioEventLoopGroup的初始化过程, 不能详细展开 ,不然就写不完了。

NioEventLoopGroup 继承关系

    public NioEventLoopGroup() {
        this(0);
    }


    public NioEventLoopGroup(int nThreads) {
        this(nThreads, (Executor) null);
    }


    public NioEventLoopGroup(int nThreads, ThreadFactory threadFactory) {
        this(nThreads, threadFactory, SelectorProvider.provider());
    }

    public NioEventLoopGroup(int nThreads, Executor executor) {
        this(nThreads, executor, SelectorProvider.provider());
    }


    public NioEventLoopGroup(
            int nThreads, ThreadFactory threadFactory, final SelectorProvider selectorProvider) {
        this(nThreads, threadFactory, selectorProvider, DefaultSelectStrategyFactory.INSTANCE);
    }

    public NioEventLoopGroup(int nThreads, ThreadFactory threadFactory,
        final SelectorProvider selectorProvider, final SelectStrategyFactory selectStrategyFactory) {
        super(nThreads, threadFactory, selectorProvider, selectStrategyFactory, RejectedExecutionHandlers.reject());
    }

    public NioEventLoopGroup(
            int nThreads, Executor executor, final SelectorProvider selectorProvider) {
        this(nThreads, executor, selectorProvider, DefaultSelectStrategyFactory.INSTANCE);
    }

    public NioEventLoopGroup(int nThreads, Executor executor, final SelectorProvider selectorProvider,
                             final SelectStrategyFactory selectStrategyFactory) {
        super(nThreads, executor, selectorProvider, selectStrategyFactory, RejectedExecutionHandlers.reject());
    }

    public NioEventLoopGroup(int nThreads, Executor executor, EventExecutorChooserFactory chooserFactory,
                             final SelectorProvider selectorProvider,
                             final SelectStrategyFactory selectStrategyFactory) {
        super(nThreads, executor, chooserFactory, selectorProvider, selectStrategyFactory,
                RejectedExecutionHandlers.reject());
    }

    public NioEventLoopGroup(int nThreads, Executor executor, EventExecutorChooserFactory chooserFactory,
                             final SelectorProvider selectorProvider,
                             final SelectStrategyFactory selectStrategyFactory,
                             final RejectedExecutionHandler rejectedExecutionHandler) {
        super(nThreads, executor, chooserFactory, selectorProvider, selectStrategyFactory, rejectedExecutionHandler);
    }

这是所有的构造方法, 如果没有指定线程数, 会由MultithreadEventLoopGroup 默认线程数指定

DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(
                "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));

还可以指定 Executor,SelectorProvider 等等, 不再赘述。

正式进入ServerBootstrap的分析, 继承于抽象父类AbstractBootstrap

b.group(accept, worker)

用于指定acceptor, worker io线程,

public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) {
        super.group(parentGroup);
        if (childGroup == null) {
            throw new NullPointerException("childGroup");
        }
        if (this.childGroup != null) {
            throw new IllegalStateException("childGroup set already");
        }
        this.childGroup = childGroup;
        return this;
    }

调用父类的方法如下:

public B group(EventLoopGroup group) {
        if (group == null) {
            throw new NullPointerException("group");
        }
        if (this.group != null) {
            throw new IllegalStateException("group set already");
        }
        this.group = group;
        return (B) this;
    }

指定Channel类型,.channel(NioServerSocketChannel.class)

AbstractBootstrap.java

public B channel(Class<? extends C> channelClass) {
        if (channelClass == null) {
            throw new NullPointerException("channelClass");
        }
        return channelFactory(new ReflectiveChannelFactory<C>(channelClass));
    }

这个ReflectiveChannelFactory会在后面的初始化Channel的时候用到.

.option(ChannelOption.SO_REUSEADDR, true)
.option(ChannelOption.SO_RCVBUF, 65535)
.option(ChannelOption.SO_BACKLOG, 1024)

用于设置ServerSocketChannel属性
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childOption(ChannelOption.SO_REUSEADDR, true)
.childOption(ChannelOption.TCP_NODELAY, true)
.childOption(ChannelOption.SO_RCVBUF, 65535)
.childOption(ChannelOption.SO_SNDBUF, 65535)

用于设置accept之后建立的SocketChannel属性
.handler(new LoggingHandler(LogLevel.INFO))

在accept过程链路中加上的 日志handler 这里涉及到ChannelPipeline,ChannelHandler,ChannelHandlerContext这三者的关系,不是这篇的核心重点, 以后可以专门写篇文章详细剖析一下。
.childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                                int len = msg.readableBytes();
                                byte[] bytes = new byte[len];
                                msg.getBytes(0, bytes);
                                System.out.println(new String(bytes));
                                String httpResponse = "HTTP/1.1 200 OK\r\n" +
                                        "Content-Length: 38\r\n" +
                                        "Content-Type: text/html\r\n" +
                                        "\r\n" +
                                        "<html><body>Hello World!</body></html>";

                                ByteBuf buffer = ctx.alloc().buffer();
                                buffer.writeBytes(httpResponse.getBytes("UTF8"));
                                ctx.writeAndFlush(buffer);
                            }
                        });
                    }
                })

在SocketChannel对应的Pipeline中添加业务handler,即对于请求的处理以及相应。

以上的都不是重点, 核心的部分来了,主要是解决 Netty 如何处理accept 以及之后的SocketChannel的初始化和读写过程。

ChannelFuture channelFuture = b.bind().awaitUninterruptibly();

bind方法就是 整个Netty启动的入口,来看看它经过了那些步骤:

AbstractBootstrap.java

    public ChannelFuture bind() {
        validate();
        SocketAddress localAddress = this.localAddress;
        if (localAddress == null) {
            throw new IllegalStateException("localAddress not set");
        }
        return doBind(localAddress);
    }

    private ChannelFuture doBind(final SocketAddress localAddress) {
        //这行代码就是如何初始化ServerSocketChannel 以及将其注册到accept 线程组 某个线程的Selector上的
        final ChannelFuture regFuture = initAndRegister();
        final Channel channel = regFuture.channel();
        if (regFuture.cause() != null) {
            return regFuture;
        }

        if (regFuture.isDone()) {
            // At this point we know that the registration was complete and successful.
            ChannelPromise promise = channel.newPromise();
            doBind0(regFuture, channel, localAddress, promise);
            return promise;
        } else {
            // Registration future is almost always fulfilled already, but just in case it's not.
            final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel);
            regFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    Throwable cause = future.cause();
                    if (cause != null) {
                        // Registration on the EventLoop failed so fail the ChannelPromise directly to not cause an
                        // IllegalStateException once we try to access the EventLoop of the Channel.
                        promise.setFailure(cause);
                    } else {
                        // Registration was successful, so set the correct executor to use.
                        // See https://github.com/netty/netty/issues/2586
                        promise.registered();

                        doBind0(regFuture, channel, localAddress, promise);
                    }
                }
            });
            return promise;
        }
    }
1. Netty对于java中ServerSocketChannel的初始化,以及注册到seletor上的过程剖析

现在来重点分析下 final ChannelFuture regFuture = initAndRegister(); 这个方法

final ChannelFuture initAndRegister() {
        Channel channel = null;
        try {
            //这行代码就是初始化ServerSocketChannle, 还记得上面channel和channelFactory的设置么? 就是用在这个地方,可以稍微看看
            channel = channelFactory.newChannel();
            init(channel);
        } catch (Throwable t) {
            if (channel != null) {

                channel.unsafe().closeForcibly();
            }

            return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
        }

        //注册channel 到accept线程组某个线程对应的selector上
        ChannelFuture regFuture = config().group().register(channel);
        if (regFuture.cause() != null) {
            if (channel.isRegistered()) {
                channel.close();
            } else {
                channel.unsafe().closeForcibly();
            }
        }
        return regFuture;
    }



ReflectiveChannelFactory.java 默认就是用的这个

public T newChannel() {
        try {
            //直接通过无参构造方法反射获得类实例 (NioServerSocketChannel.class)
            return clazz.newInstance();
        } catch (Throwable t) {
            throw new ChannelException("Unable to create Channel from class " + clazz, t);
        }
    }


NioServerSocketChannel.java 的初始化

    public NioServerSocketChannel() {
        this(newSocket(DEFAULT_SELECTOR_PROVIDER));
    }

    private static ServerSocketChannel newSocket(SelectorProvider provider) {
        try {
            //获取java中的ServerSocketChannel
            return provider.openServerSocketChannel();
        } catch (IOException e) {
            throw new ChannelException(
                    "Failed to open a server socket.", e);
        }
    }

    /**
     * Create a new instance using the given {@link SelectorProvider}.
     */
    public NioServerSocketChannel(SelectorProvider provider) {
        this(newSocket(provider));
    }

    /**
     * Create a new instance using the given {@link ServerSocketChannel}.
     */
    public NioServerSocketChannel(ServerSocketChannel channel) {
        //调用父类的构造方法 设置interest ops SelectionKey.OP_ACCEPT
        super(null, channel, SelectionKey.OP_ACCEPT);
        //ServerScoketChannel的配置 等会儿会将上面的option的参数 设置进入javaChannel().socket()(也就是上面newSocket获得的)
        config = new NioServerSocketChannelConfig(this, javaChannel().socket());
    }


AbstractNioChannel.java  设置interest ops SelectionKey.OP_ACCEPT 并且设置ch.configureBlocking(false);
protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
        super(parent);
        this.ch = ch;
        this.readInterestOp = readInterestOp;
        try {
            ch.configureBlocking(false);
        } catch (IOException e) {
            try {
                ch.close();
            } catch (IOException e2) {
                if (logger.isWarnEnabled()) {
                    logger.warn(
                            "Failed to close a partially initialized socket.", e2);
                }
            }

            throw new ChannelException("Failed to enter non-blocking mode.", e);
        }
    }


server register to selector 过程
SingleThreadEventLoop.java
public ChannelFuture register(final ChannelPromise promise) {
        ObjectUtil.checkNotNull(promise, "promise");
        //unsafe在channel初始化也就是new的时候就会构造一个对应的,代码在其父类AbstractChannel中 可以稍微看下
         promise.channel().unsafe().register(this, promise);
        return promise;
    }

unsafe 和pipeline 初始化,有兴趣的可以自己看下
    protected AbstractChannel(Channel parent, ChannelId id) {
        this.parent = parent;
        this.id = id;
        unsafe = newUnsafe();
        pipeline = newChannelPipeline();
    }

register 注册过程最终是在unsafe中完成的  看看
    @Override
    protected AbstractNioUnsafe newUnsafe() {
        //NioServerSocketChannel 的unsafe是NioMessageUnsafe
        return new NioMessageUnsafe();
    }

第一步 AbstractUnsafe.java
    public final void register(EventLoop eventLoop, final ChannelPromise promise) {
            if (eventLoop == null) {
                throw new NullPointerException("eventLoop");
            }
            if (isRegistered()) {
                promise.setFailure(new IllegalStateException("registered to an event loop already"));
                return;
            }
            if (!isCompatible(eventLoop)) {
                promise.setFailure(
                        new IllegalStateException("incompatible event loop type: " + eventLoop.getClass().getName()));
                return;
            }

            //将accept中某个eventLoop绑定到该NioServerSocketChannel上,意味着 一个channel 只能对应一个线程, 而一个线程可以绑定多个channel, 这也就是一个pipeline中的handler只能由某一个线程来处理,也就是不存在多线程竞争的情况,Netty特性之一,体现在这。
            AbstractChannel.this.eventLoop = eventLoop;

            //这里判断就是为了应对上面的特性而设的 只能由channel绑定的线程来处理
            if (eventLoop.inEventLoop()) {
                register0(promise);
            } else {
                try {
                    eventLoop.execute(new Runnable() {
                        @Override
                        public void run() {
                            register0(promise);
                        }
                    });
                } catch (Throwable t) {
                    logger.warn(
                            "Force-closing a channel whose registration task was not accepted by an event loop: {}",
                            AbstractChannel.this, t);
                    closeForcibly();
                    closeFuture.setClosed();
                    safeSetFailure(promise, t);
                }
            }
        }

private void register0(ChannelPromise promise) {
            try {

                if (!promise.setUncancellable() || !ensureOpen(promise)) {
                    return;
                }
                boolean firstRegistration = neverRegistered;
                //register 
                doRegister();
                neverRegistered = false;
                registered = true;


                pipeline.invokeHandlerAddedIfNeeded();

                safeSetSuccess(promise);
                pipeline.fireChannelRegistered();


                if (isActive()) {
                    if (firstRegistration) {
                        pipeline.fireChannelActive();
                    } else if (config().isAutoRead()) {

                        beginRead();
                    }
                }
            } catch (Throwable t) {
                // Close the channel directly to avoid FD leak.
                closeForcibly();
                closeFuture.setClosed();
                safeSetFailure(promise, t);
            }
        }

AbstractNioChannel.java
    protected void doRegister() throws Exception {
        boolean selected = false;
        for (;;) {
            try {
            //终于看到了java中熟悉的代码了 至此 server register accept to selector 过程全部结束 对与accept后 的SocketChannel的注册读写事件过程也是大同小异
                selectionKey = javaChannel().register(eventLoop().unwrappedSelector(), 0, this);
                return;
            } catch (CancelledKeyException e) {
                if (!selected) {

                    eventLoop().selectNow();
                    selected = true;
                } else {

                    throw e;
                }
            }
        }
    }

重新回到initAndRegister()这个过程 ,完了之后,会调用抽象init()方法,有两种实现 ServerBootstrap(服务端) 和Bootstrap (客户端),这里主要是看服务端的过程:

void init(Channel channel) throws Exception {
        final Map<ChannelOption<?>, Object> options = options0();
        synchronized (options) {
            //这里的set option 就是上面说的对于ServerSocketChannel属性的设置,有兴趣的可以自己看,比较简单,就不展开了
            setChannelOptions(channel, options, logger);
        }

        final Map<AttributeKey<?>, Object> attrs = attrs0();
        synchronized (attrs) {
            for (Entry<AttributeKey<?>, Object> e: attrs.entrySet()) {
                @SuppressWarnings("unchecked")
                AttributeKey<Object> key = (AttributeKey<Object>) e.getKey();
                channel.attr(key).set(e.getValue());
            }
        }

        ChannelPipeline p = channel.pipeline();

        final EventLoopGroup currentChildGroup = childGroup;
        final ChannelHandler currentChildHandler = childHandler;
        final Entry<ChannelOption<?>, Object>[] currentChildOptions;
        final Entry<AttributeKey<?>, Object>[] currentChildAttrs;
        synchronized (childOptions) {
            currentChildOptions = childOptions.entrySet().toArray(newOptionArray(childOptions.size()));
        }
        synchronized (childAttrs) {
            currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(childAttrs.size()));
        }

        //这里很重要 会处理accept 进来的SocketChannel 通过 ServerBootstrapAcceptor这个hanadler
        p.addLast(new ChannelInitializer<Channel>() {
            @Override
            public void initChannel(final Channel ch) throws Exception {
                final ChannelPipeline pipeline = ch.pipeline();
                ChannelHandler handler = config.handler();
                if (handler != null) {
                    pipeline.addLast(handler);
                }

                ch.eventLoop().execute(new Runnable() {
                    @Override
                    public void run() {
                        pipeline.addLast(new ServerBootstrapAcceptor(
                                ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
                    }
                });
            }
        });
    }

先来看看 server处理SocketChannel的过程 ,等会儿再来看是如何进行accept过程并把获得的SocketChannel发送到该ServerBootstrapAcceptor  handler中进行处理的


    public void channelRead(ChannelHandlerContext ctx, Object msg) {
            //接受到的Channel其实是NioSocketChannel 里面封装有java nio中的SocketChannel accept之后获得的
            final Channel child = (Channel) msg;

            //为NioSocketChannel设置netty启动时设置的childHanlder
            child.pipeline().addLast(childHandler);

            //为SocketChannel设置child option 属性
            setChannelOptions(child, childOptions, logger);

            for (Entry<AttributeKey<?>, Object> e: childAttrs) {
                child.attr((AttributeKey<Object>) e.getKey()).set(e.getValue());
            }

            try {
                //向worker 线程组的某个线程的selector register注册io事件, 和上面注册accept io事件大同小异, 不再赘述
                childGroup.register(child).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (!future.isSuccess()) {
                            forceClose(child, future.cause());
                        }
                    }
                });
            } catch (Throwable t) {
                forceClose(child, t);
            }
        }


接下来看看accept这个过程,因为上面ServerSocketChannel已经注册了accept事件,一旦有客户端accept就绪,就会触发此事件, 可以简单的来看看NioEventLoop中对于selector io 事件的处理过程, 不详细了



private void processSelectedKey(SelectionKey k, AbstractNioChannel ch) {
        //这里就是上面的NioServerSocketChannel 的NioMessageUnsafe
        final AbstractNioChannel.NioUnsafe unsafe = ch.unsafe();
        if (!k.isValid()) {
            final EventLoop eventLoop;
            try {
                eventLoop = ch.eventLoop();
            } catch (Throwable ignored) {
                return;
            }


            unsafe.close(unsafe.voidPromise());
            return;
        }

        try {
            int readyOps = k.readyOps();

            if ((readyOps & SelectionKey.OP_CONNECT) != 0) {

                int ops = k.interestOps();
                ops &= ~SelectionKey.OP_CONNECT;
                k.interestOps(ops);

                unsafe.finishConnect();
            }


            if ((readyOps & SelectionKey.OP_WRITE) != 0) {

                ch.unsafe().forceFlush();
            }


            if ((readyOps & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0 || readyOps == 0) {
                //当有客户端accept事件就绪的时候,
                unsafe.read();
            }
        } catch (CancelledKeyException ignored) {
            unsafe.close(unsafe.voidPromise());
        }
    }



    //unsafe.read(); accept处理过程
    private final class NioMessageUnsafe extends AbstractNioUnsafe {

        private final List<Object> readBuf = new ArrayList<Object>();

        @Override
        public void read() {
            assert eventLoop().inEventLoop();
            final ChannelConfig config = config();
            final ChannelPipeline pipeline = pipeline();
            //RecvByteBufAllocator 读取输入数据存入的ByteBuf分配器
            final RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle();
            allocHandle.reset(config);

            boolean closed = false;
            Throwable exception = null;
            try {
                try {
                    do {
                    //accept 入口 看doReadMessages NioServerSocketChannel的实现
                        int localRead = doReadMessages(readBuf);
                        if (localRead == 0) {
                            break;
                        }
                        if (localRead < 0) {
                            closed = true;
                            break;
                        }

                        allocHandle.incMessagesRead(localRead);
                    } while (allocHandle.continueReading());
                } catch (Throwable t) {
                    exception = t;
                }

                int size = readBuf.size();
                for (int i = 0; i < size; i ++) {
                    readPending = false;
                    pipeline.fireChannelRead(readBuf.get(i));
                }
                readBuf.clear();
                allocHandle.readComplete();
                pipeline.fireChannelReadComplete();

                if (exception != null) {
                    closed = closeOnReadError(exception);

                    pipeline.fireExceptionCaught(exception);
                }

                if (closed) {
                    inputShutdown = true;
                    if (isOpen()) {
                        close(voidPromise());
                    }
                }
            } finally {

                if (!readPending && !config.isAutoRead()) {
                    removeReadOp();
                }
            }
        }
    }


    protected int doReadMessages(List<Object> buf) throws Exception {
        //accept 在此 这里很简单 方法里面主逻辑就是serverSocketChannel.accept()
        SocketChannel ch = SocketUtils.accept(javaChannel());

        try {
            if (ch != null) {
                //把SocketChannel 封装进入NioSocketChannel 在通过上面的read方法 int size = readBuf.size();
                //for (int i = 0; i < size; i ++) {
                    //readPending = false;
                    //调用下一个inbound的handler,直到到达ServerBootstrapAcceptor这个handler 中 调用channelRead方法 于是就完成了整个accept过程,还是有点小复杂的啊
                    //pipeline.fireChannelRead(readBuf.get(i));
                //}
                buf.add(new NioSocketChannel(this, ch));
                return 1;
            }
        } catch (Throwable t) {
            logger.warn("Failed to create a new channel from an accepted socket.", t);

            try {
                ch.close();
            } catch (Throwable t2) {
                logger.warn("Failed to close a socket.", t2);
            }
        }

        return 0;
    }

到此就差不多结束,简单的过了一下,篇幅不够 ,要想详细了解其过程,还得看源码。

四、netty源码分析之ServerBootstrap 一、功能概述 前两篇我们分别介绍了EventLoopGroup和EventLoop在netty中的作用。但是仅仅知道这些,可能对netty如何完成一整个网络事件监控到任务分发处理还是有些模糊。本篇我们要分析一下netty的启动流程。在我们使用netty编程的时候,我们的使用ServerBootstrap和Bootstrap来实现服务端和客户端的启动。我们先来看一下这两个类的相关类图: netty... 阅读详情

相关推荐

netty案例,netty4.1源码分析篇二《ServerBootstrap配置与绑定启动》

结合上一章节介绍NioEventLoopGroup,本章节继续介绍ServerBootstrap相关代码。 启动NettyServer的模版代码 private void bing(int port) { EventLoopGroup parentGroup = new NioEventLoopGroup(); EventLoopGroup childGroup = new ...

bugstack虫洞栈 1867

Netty之ServerBootstrap详解与实战

是Netty用于启动服务器的助手类,它提供了一系列的流式方法来配置服务器的网络层选项、线程模型和业务处理逻辑。通过,用户可以轻松地设置服务器监听端口、初始化通道(Channel)以及绑定事件处理器等。是一个启动NIO服务的辅助启动类。它可以配置服务器的一系列参数,比如端口、用于处理业务逻辑的等。通过使用,开发者可以轻松地启动一个服务端Channel,监听并接受客户端的连接请求。

HaSaKing的博客 4084

谷粒商城篇章9 ---- P248-P261/P292-P294 ---- 消息队列【分布式高级篇六】

RabbitMQ消息队列、RabbitMQ延时队列。

weixin_48568302的博客 1561

Netty中ServerBootstrap类介绍

Netty中的核心类之一:ServerBootstrap类。

小飞侠的博客 3083

ARM CMSIS DAP源码分析(二)

今天分析的是RDDI_DAP_GetARMRegs(DWORD *regs, DWORD *rfpu, ULONG64 mask)和RDDI_DAP_SetARMRegs(DWORD *regs, DWORD *rfpu, ULONG64 mask)这两个函数。 以RDDI_DAP_GetARMRegs(DWORD *regs, DWORD *rfpu, ULONG64 mask)为例,代码如下:

pengxiao618的专栏 7981

MySQL安装配置教程(超级详细)

一、 下载MySQL Mysql官网下载地址:MySQL :: Download MySQL Installer (Archived Versions) 1. 选择要安装的版本,本篇文章选择的是5.7.31版本,点击Download下载 正在上传…重新上传取消 二、 安装MySQL 1. 选择设置类型双击运行mysql-installer-community-5.7.31.0.msi 这里选择是自定义安装,所以直接选择“Custom”,点击“Next” “Developer Default”是

m0_67322837的博客 5万+

Netty教程-ServerBootstrap

ServerBootstrap介绍ServerBootstrap也继承AbstractBootstrap,所以ServerBootstrap和Bootstrap的结构是差不多的,但是ServerBootstrap负责初始化netty服务器,并且开始监听端口的socket请求。EchoServer先看看Netty自带的EchoServer例子:public final class EchoServer

于宝龙的博客 6025

【超详细】安装了anaconda后,Ubuntu18+COLMAP配置疯狂踩坑踩至魔怔的记录

本博客收集了博主在Ubuntu18系统中编译COLMAP所遇到的困难,提供了解决方法,也收集了目前网上大多数的坑,除此之外,也为Ubuntu18系统下COLMAP的安装提供了一种新的路径。

Stay_Foo_lish的博客 3516

Netty Bootstrap/ServerBootstrap

Netty中的Bootstrap和ServerBootstrap是Netty框架中的两个核心引导类,它们分别用于客户端和服务端的启动配置。

王小工小工历程 1839

智慧加油站小程序数据库设计文档

【代码】智慧加油站小程序数据库设计文档。

低代码布道师的博客 1408

Spring 核心技术解析【纯干货版】- I:Spring 基础模块 Spring-Core 模块精讲

Spring-Core 模块,是 Spring 核心容器模块之一。虽然 “Core” 本身就有 “核心的,重要的部分” 的含义,但是它并非是实现(常被我们说为 Spring 核心机制)IOC / AOP 的模块。Spring 中的 IOC 机制,主要来自于 BeanFactory 容器和 ApplicationContext 容器,这二者分别由同为核心容器模块的 Spring-Bean 模块 和 Spring-Context 模块所提供。

栗筝i的博客 2536

[Netty-4.1.9.Final源码解析系列]-4-Bootstrap属性设置

4 ServerBootstrap属性 设置 在服务端示例中,我们已经创建了ServerBootstrap对象和EventLoopGroup对象,ServerBootstrap用来启动服务端,EventLoopGroup用来处理事件轮训,我们接下来看下EventLoopGroup类型对象是如何配置在ServerBootstrap类型中的 示例代码如下: EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup wor

宋小生-中间件 860

国社科基金申报书“选题与说明依据”用AI怎么写?借助Gemini 3 Pro一次理清研究演进逻辑

研究进展部分要明确指出已有研究的不足与局限,比如方法不足、数据或材料受限、研究视角单一等等局限,之后要找准研究切入点,自然引申出自己的研究问题。为提升课题申报书的质量,学术史梳理要遵循述评结合、中外结合、新老结合的原则,不仅“述”,更要“评”,兼顾国内研究与国际学术动态,统筹经典研究与最新成果。它是对选题的整体概述,需阐明研究的具体问题、视角以及核心概念。2)存在问题或争议:结合已有研究或实践现状,指出该领域在理论建构、测量工具、实践应用或研究结论方面仍存在的不足、空白或争议,明确研究的必要性;

智能AI让学术科研更容易 959

netty源码分析一

前段时间比较忙,没有时间去学习啦,现在稍微好一点啦,看着自己年初定下的目标,还有很多没有完成的呀。从下阶段起学习netty框架啦,之前也了解netty框架,但是没有深入理解,现在好好学习一下。 学习netty框架之前,要了解java nio基本知识java nio常见的API有 channel  channel可以理解为通道,其中包括TCP/UDP还有文件 FileChannelDat

hy614的专栏 558

XSS漏洞之PDF生成:从XSS到服务端任意文件读取

XSS是最为常见的Web漏洞之一,多年来连续入选OWASP TOP10,相信大家都耳熟能详。 它是一种代码注入类的攻击,是一种客户端侧的攻击,攻击者通过在Web应用中注入恶意JavaScript代码,通过点击URL,最终在受害者浏览器端执行的一种漏洞。主要有反射型XSS、存储型XSS、基于DOM的XSS三类。XSS一些比较常规的危害大概有:重定向浏览器、窃取Cookie、浏览器劫持等。本文章侧重于发现XSS后的进一步利用。 主要介绍在某次实际测试过程中,发现XSS漏洞之后,如何进一步的利用,最终通过XSS达

计算机毕业论文源码,学生个人网页制作html源码。贴近用户做网络推广和互联网优化。 3793

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

Netty源码分析:ServerBootstrap

Netty学习笔记:ServerBootstrap一般服务端的代码如下所示: package com.wrh.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; imp

wojiushimogui的博客 2035

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

01 | ServerBootstrap源码分析(一)

对于netty框架,大家有一些习惯性的概念,比如线程模型、IO模型,网上有一大堆概念,每次都是看完一篇帖子就理解了,过了一会就忘记了,下面就简单讲一下吧。为什么叫EventLoopGroup是线程模型?EventLoopGroup可以认为是netty对线程模型的一种实现,因为其对NioEventLoop的这个IO模型的一种实现,他可以管理多个NioEventLoop,内部还有实现了一个选择器EventExecutorChooser的实现。

qiushily2030的博客 1026

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

Netty之ServerBootstrap源码分析

本文是对Netty的服务端ServerBootstrap类的简单分析,以此来学习Netty源码的设计思想,通过本文你将了解Netty是如何创建启动类的,如有错误请指出,谢谢。 ServerBootstrap启动 1.构造启动类 # 创建启动类 ServerBootstrap bootstrap = new ServerBootstrap(); 2.注册基本信息 # 1.group:将创建的bossGroup与workerGroup线程组添加到启动类中 # 2.channel:设置创建消息事件传输的管道.

qq_37803406的博客 393

Netty 核心源码解析

Netty 第一讲:Netty 架构与原理本文是《Netty 三讲》的第二讲:Netty 核心源码解析(部分),大纲如下:前言1. Netty 服务端启动过程源码剖析1.1. 执行 ne...

weixin_41385912的博客 1万+

十三、Netty核心源码分析之启动过程剖析

画外音 本文使用的是 4.1.20 版本的 netty 源码。netty 源码包的总体结构如下,在 io.netty.example 中,官方给我们提供了很多的实例供我们参考。有项目实战需求的读者在了解了 Netty 的工作原理和常用 API 之后,可以参考这个包中的案例构建自己的网络 IO 程序。 因为这篇文章是对netty的源码进行分析,所以篇幅可能会较长,博主尽量 用通俗易懂的语言以及较易理解的分析图为大家呈现,如果能坚持到阅读到最后,就足以说明你已经很棒了 ✌️ ✌️ ✌️ !!! 一、1.

猿小许的博客 930

【Netty4】Netty服务端启动源码分析(一)

http://ifeve.com/netty-reactor-4/ https://blog.csdn.net/huanshirenjian/article/details/90228894

m0_45406092的博客 457

Netty源码分析专题[1]-服务端启动流程

Netty源码分析专题[1]-服务端启动流程   Netty是一个高性能底层网络传输层技术,深入研究其底层实现原理不仅可以领略其优秀的架构思想,还能为用好这个技术打下坚实的基础,正所谓知其然知其所以然,本文使用的netty版本是4.1.52,其中池化内存部分的源码的变动很大,这个版本的代码在内存回收到缓存的时候有个bug,当然新版本已经修复,具体的可以看池化内存源码分析相关的内容。   从本文开始,会有一系列的Netty源码分析相关的分析 1、从Java NIO模型说起   Java NIO类库好像是JDK

unlock的博客 1251

Netty4.x.x启动过程源码分析

在分析代码之前不得不先了解下netty的线程模型,脑中有了概念之后后续的代码才好理解。由于没有称手的工具,就不画图了(其实就是懒T_T).百度上一大堆。 一、netty4.x.x线程模型 Netty4.x.x主要靠两个Reactor(事件驱动)线程组(线程池)维持工作,一个线程组(pare...

chuankuizong8056的博客 199

【Netty源码分析】01 Netty Server 启动流程 上

Netty服务端一般如下面代码模式,简化了NIO编程的复杂性同时,并且借助于Pipeline模型,可以很简单的就构建出高性能、可扩展的应用程序。publicclassDemoServ...

god_86的专栏 297

Netty核心源码分析(一),Netty的Server端启动过程源码分析

(2) 创建了一个唯一的 ChannelId,创建了一个 NioMessageUnsafe,用于操作消息,创建了个 DefaultChannelPipeline 管道,是个双向链表结构,用于过滤所有的进出的消息。我们可以看到,addLast方法并不是将Handler放到了最后,而是将我们自定义的Handler放到了tail的前一个,这样tail永远会在最后面,做一些系统的固定工作。最终是获取了CPU核心数 * 2,并创建这些线程,我本机CPU是20核,所以创建了40个workerGroup线程。

秃了也弱了 1229

【1.1】ServerBootStrap源码分析

文章目录 一、ServerBootstrap分析 (1.1)ServerBootstrap类的继承结构 (1.2)构建者模式? (1.3)ServerBootstrap及父类的源码 二、方法链 (2.1)group() (2.2)channel() (2.3)handler() (2.4)childHandler() 三、绑定端口 (3.1)bind() 一、ServerBootstrap分析 ...

无敌兔0x01 601
上一篇: 从零开始学Scala系列(六)之类(Classes)和对象(Objects)
下一篇: 字符集编码 Unicode UTF8 UTF16 UTF32 和BOM(Byte Order Mark)
rodbate
博客等级 码龄11年 17粉丝 23原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值