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;
            }
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章