netty-服务器端启动流程

318 阅读2分钟

类的继承图

说明
1.服务器端启动类ServerBootStrap
2.客户端启动类BootStrap


抽象类
作用
是一个工具类 创建连接(netty叫channel) 和ServerSocket创建连接一样

哪些方法?
bind() ip/port server和client 通用的方法 不通用的方法由子类实现

API
AbstractBootstrap is a helper class that makes it easy to bootstrap a Channel. //是一个工具类

It support method-chaining to provide an easy way to configure the AbstractBootstrap.

When not used in a ServerBootstrap context, the bind() methods are useful for connectionless transports such as datagram (UDP).

添加EventExecutorGroup

public abstract class MultithreadEventExecutorGroup extends AbstractEventExecutorGroup {


protected MultithreadEventExecutorGroup(int nThreads, Executor executor,

                                            EventExecutorChooserFactory chooserFactory, Object... args) {

        if (nThreads <= 0) {

            throw new IllegalArgumentException(String.format("nThreads: %d (expected: > 0)", nThreads));

        }



        if (executor == null) {

            executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());

        }



        children = new EventExecutor[nThreads];



        for (int i = 0; i < nThreads; i ++) {

            boolean success = false;

            try {

                children[i] = newChild(executor, args);

                success = true;

            } catch (Exception e) {

                // TODO: Think about if this is a good exception type

                throw new IllegalStateException("failed to create a child event loop", e);

            } finally {

                if (!success) {

                    for (int j = 0; j < i; j ++) {

                        children[j].shutdownGracefully();

                    }



                    for (int j = 0; j < i; j ++) {

                        EventExecutor e = children[j];

                        try {

                            while (!e.isTerminated()) {

                                e.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);

                            }

                        } catch (InterruptedException interrupted) {

                            // Let the caller handle the interruption.

                            Thread.currentThread().interrupt();

                            break;

                        }

                    }

                }

            }

        }



        chooser = chooserFactory.newChooser(children);



        final FutureListener<Object> terminationListener = new FutureListener<Object>() {

            @Override

            public void operationComplete(Future<Object> future) throws Exception {

                if (terminatedChildren.incrementAndGet() == children.length) {

                    terminationFuture.setSuccess(null);

                }

            }

        };



        for (EventExecutor e: children) {

            e.terminationFuture().addListener(terminationListener);

        }



        Set<EventExecutor> childrenSet = new LinkedHashSet<EventExecutor>(children.length);

        Collections.addAll(childrenSet, children);

        readonlyChildren = Collections.unmodifiableSet(childrenSet);

    }


bind

private static void doBind0(

            final ChannelFuture regFuture, final Channel channel,

            final SocketAddress localAddress, final ChannelPromise promise) {



        // This method is invoked before channelRegistered() is triggered.  Give user handlers a chance to set up

        // the pipeline in its channelRegistered() implementation.

        channel.eventLoop().execute(new Runnable() { //提交/执行任务

            @Override

            public void run() { //业务方法

                if (regFuture.isSuccess()) {

                    channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE); //

                } else {

                    promise.setFailure(regFuture.cause());

                }

            }

        });

    }


 @Override

    public ChannelFuture bind(final SocketAddress localAddress, final ChannelPromise promise) {

        if (localAddress == null) {

            throw new NullPointerException("localAddress");

        }

        if (!validatePromise(promise, false)) {

            // cancelled

            return promise;

        }



        final AbstractChannelHandlerContext next = findContextOutbound();

        EventExecutor executor = next.executor();

        if (executor.inEventLoop()) {

            next.invokeBind(localAddress, promise);

        } else {

            safeExecute(executor, new Runnable() {

                @Override

                public void run() {

                    next.invokeBind(localAddress, promise);

                }

            }, promise, null);

        }

        return promise;

    }


abstract class AbstractChannelHandlerContext extends DefaultAttributeMap

        implements ChannelHandlerContext, ResourceLeakHint {


@Override

    public ChannelFuture connect(

            final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) {



        if (remoteAddress == null) {

            throw new NullPointerException("remoteAddress");

        }

        if (!validatePromise(promise, false)) {

            // cancelled

            return promise;

        }



        final AbstractChannelHandlerContext next = findContextOutbound();

        EventExecutor executor = next.executor();

        if (executor.inEventLoop()) {

            next.invokeConnect(remoteAddress, localAddress, promise);

        } else {

            safeExecute(executor, new Runnable() {

                @Override

                public void run() {

                    next.invokeConnect(remoteAddress, localAddress, promise);

                }

            }, promise, null);

        }

        return promise;

    }


class ServerSocketChannelImpl

    extends ServerSocketChannel

    implements SelChImpl

{


@Override

    public ServerSocketChannel bind(SocketAddress local, int backlog) throws IOException {

        synchronized (lock) {

            if (!isOpen())

                throw new ClosedChannelException();

            if (isBound())

                throw new AlreadyBoundException();

            InetSocketAddress isa = (local == null) ? new InetSocketAddress(0) :

                Net.checkAddress(local);

            SecurityManager sm = System.getSecurityManager();

            if (sm != null)

                sm.checkListen(isa.getPort());

            NetHooks.beforeTcpBind(fd, isa.getAddress(), isa.getPort());

            Net.bind(fd, isa.getAddress(), isa.getPort()); //最终还是调用ServerSocketChannelImpl.bind
            Net.listen(fd, backlog < 1 ? 50 : backlog); 

            synchronized (stateLock) {

                localAddress = Net.localAddress(fd);

            }

        }

        return this;

    }


addListener()

public class DefaultChannelPromise extends DefaultPromise<Void> implements ChannelPromise, FlushCheckpoint {


@Override

    public ChannelPromise addListener(GenericFutureListener<? extends Future<? super Void>> listener) {

        super.addListener(listener);

        return this;

    }