Netty源碼分析系列--5.ServerBootStrap綁定端口號

前文Netty源碼分析系列--3. 服務(wù)器啟動ServerBootStrap分析中介紹了對ServerBootStrap的多個變量賦值后发绢,下一步就要綁定端口號啟動服務(wù)器。

    ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();

調(diào)用bind(8899)進入抽象類AbstractBootStrapdoBind方法:

 private ChannelFuture doBind(final SocketAddress localAddress) {
    final ChannelFuture regFuture = initAndRegister();
    final Channel channel = regFuture.channel();
    if (regFuture.cause() != null) {
        return regFuture;
    }

    if (regFuture.isDone()) {
        ChannelPromise promise = channel.newPromise();
        doBind0(regFuture, channel, localAddress, promise);
        return promise;
    } else {
        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) {
                    promise.setFailure(cause);
                } else {
                    promise.registered();
                    doBind0(regFuture, channel, localAddress, promise);
                }
            }
        });
        return promise;
    }
}

其中關(guān)鍵的方法是:

  • intAndRegister()
  • ChannelFuture類型的對象regFuture添加監(jiān)聽器锌俱,當(dāng)IO操作完成時執(zhí)行回調(diào)方法operationComplete毫胜。

1 . 先關(guān)注第1行initAndRegister方法如下:其中channelFactory.newChannel()就是使用之前channel方法中創(chuàng)建的ReflectiveChannelFactory通過反射新建NioServerSocketChannel實例箕憾。

  final ChannelFuture initAndRegister() {
    Channel channel = null;
    try {
        channel = channelFactory.newChannel();
        init(channel);
    } catch (Throwable t) {
        if (channel != null) {
            // channel can be null if newChannel crashed (eg SocketException("too many open files"))
            channel.unsafe().closeForcibly();
            // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor
            return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
        }
        // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor
        return new DefaultChannelPromise(new FailedChannel(), GlobalEventExecutor.INSTANCE).setFailure(t);
    }

    ChannelFuture regFuture = config().group().register(channel);
    if (regFuture.cause() != null) {
        if (channel.isRegistered()) {
            channel.close();
        } else {
            channel.unsafe().closeForcibly();
        }
    }

    return regFuture;
  }

NioServerSocketChannel類的構(gòu)造函數(shù):靜態(tài)變量DEFAULT_SELECTOR_PROVIDER使用了NIO Selector Provider,構(gòu)造函數(shù)中調(diào)用靜態(tài)方法newSocket伦连。

使用provider.openServerSocketChannel()創(chuàng)建NioServerSocketChannel雨饺。

    private static final SelectorProvider DEFAULT_SELECTOR_PROVIDER = SelectorProvider.provider();
   
    private static ServerSocketChannel newSocket(SelectorProvider provider) {
      try {
          return provider.openServerSocketChannel();
       } catch (IOException e) {
          throw new ChannelException(
                "Failed to open a server socket.", e);
      }
     }
     public NioServerSocketChannel() {
           this(newSocket(DEFAULT_SELECTOR_PROVIDER));
    }

2. initAndRegister中使用ChannelFactory創(chuàng)建完Channel后钳垮,調(diào)用了init進行初始化。

  void init(Channel channel) throws Exception {

    //以上省略......
    ChannelPipeline p = channel.pipeline();

    final EventLoopGroup currentChildGroup = childGroup;
    final ChannelHandler currentChildHandler = childHandler;
     //省略部分代碼......

    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));
                }
            });
        }
    });
}

獲得channel對象的pipleline额港,如果有配置handler對象如LoggingHandler(LogLevel.INFO)饺窿,會加入到pipeline中。

注意:這里出現(xiàn)了一個類ServerBootstrapAcceptor移斩,稍后會介紹肚医。

3. initAndRegister中:

   ChannelFuture regFuture = config().group().register(channel);

上面代碼group()獲得bossGroup對象,并將channel注冊到該EventLoopGroup向瓷。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末肠套,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子猖任,更是在濱河造成了極大的恐慌你稚,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,122評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件超升,死亡現(xiàn)場離奇詭異入宦,居然都是意外死亡,警方通過查閱死者的電腦和手機室琢,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來落追,“玉大人盈滴,你說我怎么就攤上這事〗文疲” “怎么了巢钓?”我有些...
    開封第一講書人閱讀 164,491評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長疗垛。 經(jīng)常有香客問我症汹,道長,這世上最難降的妖魔是什么贷腕? 我笑而不...
    開封第一講書人閱讀 58,636評論 1 293
  • 正文 為了忘掉前任背镇,我火速辦了婚禮,結(jié)果婚禮上泽裳,老公的妹妹穿的比我還像新娘瞒斩。我一直安慰自己,他們只是感情好涮总,可當(dāng)我...
    茶點故事閱讀 67,676評論 6 392
  • 文/花漫 我一把揭開白布胸囱。 她就那樣靜靜地躺著,像睡著了一般瀑梗。 火紅的嫁衣襯著肌膚如雪烹笔。 梳的紋絲不亂的頭發(fā)上裳扯,一...
    開封第一講書人閱讀 51,541評論 1 305
  • 那天,我揣著相機與錄音谤职,去河邊找鬼饰豺。 笑死,一個胖子當(dāng)著我的面吹牛柬帕,可吹牛的內(nèi)容都是我干的哟忍。 我是一名探鬼主播,決...
    沈念sama閱讀 40,292評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼陷寝,長吁一口氣:“原來是場噩夢啊……” “哼锅很!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起凤跑,我...
    開封第一講書人閱讀 39,211評論 0 276
  • 序言:老撾萬榮一對情侶失蹤爆安,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后仔引,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體扔仓,經(jīng)...
    沈念sama閱讀 45,655評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,846評論 3 336
  • 正文 我和宋清朗相戀三年咖耘,在試婚紗的時候發(fā)現(xiàn)自己被綠了翘簇。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,965評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡儿倒,死狀恐怖版保,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情夫否,我是刑警寧澤彻犁,帶...
    沈念sama閱讀 35,684評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站凰慈,受9級特大地震影響汞幢,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜微谓,卻給世界環(huán)境...
    茶點故事閱讀 41,295評論 3 329
  • 文/蒙蒙 一森篷、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧堰酿,春花似錦疾宏、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,894評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春岩馍,著一層夾襖步出監(jiān)牢的瞬間碉咆,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,012評論 1 269
  • 我被黑心中介騙來泰國打工蛀恩, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留疫铜,地道東北人。 一個月前我還...
    沈念sama閱讀 48,126評論 3 370
  • 正文 我出身青樓双谆,卻偏偏與公主長得像壳咕,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子顽馋,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,914評論 2 355

推薦閱讀更多精彩內(nèi)容