Jetty源碼分析(三)---Connector組件

jetty的請求過程

  1. ServerConnector.doStart調用open打開ServerSocketChannel
public void open() throws IOException
{   
     //打開端口
     _acceptChannel = openAcceptChannel();
     _acceptChannel.configureBlocking(true);        
 }
  1. AbstractConnector.doStart創建Acceptor去監聽請求鏈接
//AbstractConnector
protected void doStart() throws Exception{
   for (int i = 0; i < _acceptors.length; i++)
        {
            //一個線程的包裝類,其處理內容見ServerConnector.accept
            Acceptor a = new Acceptor(i);
            getExecutor().execute(a);
        }
}

//Acceptor類的具體調用
//ServerConnector
public void accept(int acceptorID) throws IOException
 {
        ServerSocketChannel serverChannel = _acceptChannel;
        if (serverChannel != null && serverChannel.isOpen())
        {
            //是否有新連接進來
            SocketChannel channel = serverChannel.accept();
            accepted(channel);
        }
}

//ServerConnector
private void accepted(SocketChannel channel) throws IOException
    {
        channel.configureBlocking(false);
        Socket socket = channel.socket();
        configure(socket);
        //把新連接交給_manager
        _manager.accept(channel);
    }
  1. SelectorManager選擇selector,並將新的channel註冊進去
//SelectorManager
 public void accept(SelectableChannel channel, Object attachment)
    {
        //選擇selector
        final ManagedSelector selector = chooseSelector();
        //最終調用 Accept.update
        selector.submit(selector.new Accept(channel, attachment));
    }
 
//Accept 
public void update(Selector selector)
{
     //channel的可讀事件監聽    
     key = channel.register(selector, 0, attachment);
     //將jetty中的包裝類EndPoint通過SelectionKey附件的功能轉發
     execute(this);    
 }   
  1. SelectorManager.doStart方法通過_strategy去啓動SelectorProducer專門消費事件
//SelectorManager.SelectorProducer
public Runnable produce()
        {
            while (true)
            {
                //取出對應任務返回並執行
                //讀寫任務最終調回ChannelEndPoint.onSelected完成
                //主要任務如下
                //1._runFillable提供的是讀操作,利用fillInterest註冊的回調,調用它的fillable方法,通常就是調用到的就是HttpConnection.onFillable方法
               //2._runCompleteWrite提供的是寫操作,從名字上來看是完成寫,其實就是在應用層拿到OutputStream往流裏面寫的時候,部分數據沒寫完,這個時候需要完成剩下的數據寫入,這裏會調用WriteFlusher來刷,WriteFlusher最終調用到EndPoint的flush,完成向Channel的寫入,這塊在下面的寫入裏面詳細講解
             //3._runCompleteWriteFillable提供先寫後讀操作,優先完成之前未完成寫入的數據,之後再執行讀操作
                Runnable task = processSelected();
                if (task != null)
                    return task;

                 //選擇有事務發生的channel,放在緩存隊列中
                if (!select())
                    return null;
            }
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章