日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

tomcat(4)Tomcat的默认连接器

發布時間:2023/12/3 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 tomcat(4)Tomcat的默认连接器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【0】README 0.0)本文部分文字描述轉自:“深入剖析tomcat”,旨在學習?tomat(4)Tomat的默認連接器 的基礎知識; 0.1)Tomcat中的連接器是一個獨立的模塊,可以插入到servlet容器中,而且還有很多連接器可以使用; 0.2)Tomcat中使用的連接器必須滿足如下要求(requirement): r1)實現 org.apache.catalina.Connector 接口; r2)負責創建實現了 org.apache.catalina.Request接口的request對象; r3)負責創建實現了 org.apache.catalina.Response接口的response對象; 0.3)連接器會等待HTTP請求,以創建request 和 response對象,然后調用 org.apache.catalina.Container接口的 invoke方法,將request對象和response對象傳給 servlet容器。invoke() 方法簽名如下:(干貨——這里涉及到類加載器) public void invoke(Request request, Response response) // SimpleContainer.invokethrows IOException, ServletException {String servletName = ( (HttpServletRequest) request).getRequestURI();servletName = servletName.substring(servletName.lastIndexOf("/") + 1);URLClassLoader loader = null;try { // 創建類加載器URL[] urls = new URL[1];URLStreamHandler streamHandler = null;File classPath = new File(WEB_ROOT);String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString() ;urls[0] = new URL(null, repository, streamHandler);loader = new URLClassLoader(urls);}catch (IOException e) {System.out.println(e.toString() );}Class myClass = null;try {myClass = loader.loadClass("servlet." + servletName);}catch (ClassNotFoundException e) {System.out.println(e.toString());}Servlet servlet = null;try {servlet = (Servlet) myClass.newInstance(); // 創建請求URI對應的servlet實例 servlet.service((HttpServletRequest) request, (HttpServletResponse) response);}......} 0.3.1)invoke方法內部:servlet容器會載入相應的servlet類,調用其 service() 方法,管理session對象,記錄錯誤消息等操作; 0.3.2)Tomcat4的默認連接器使用了一些優化方法:一、使用了一個對象池來避免了頻繁創建對象帶來的性能損耗;二、在很多地方,Tomcat4 的默認連接器使用了字符數組來代替字符串;(干貨——Tomcat4的默認連接器使用了一些優化方法 0.4)for complete source code, please visit?https://github.com/pacosonTang/HowTomcatWorks/tree/master/chapter4; 0.5)本文講解的是 tomcat中的默認連接器,而 這篇博文?tomcat(3)連接器?講解的是以前的前輩自定義的連接器(功能和tomcat默認連接器類似),這旨在學習 tomcat中默認連機器的原理。 0.6)溫馨建議:建議閱讀本文之前,已閱讀過 tomcat(1~3)的系列文章,因為它們是環環相扣的;

【1】HTTP 1.1 的新特性 【1.1】持久連接 1)intro to persistent connect:在HTTP1.1之前, 無論瀏覽器何時連接到web server,當server返回請求資源后,會斷開與瀏覽器的連接,但網頁上會包含一些其他資源,如圖片;所以,當請求一個頁面時,瀏覽器還需要下載這些被頁面引用的資源。如果頁面和它引用的所有資源文件都使用不同的連接進行下載的話,處理過程會很慢;這也就是為什么會引入持久連接;(干貨——引入持久連接的原因) 1.1)使用持久連接后,當下載了頁面后,server并不會立即關閉連接,相反,它會等待web client請求被該頁面引用的所有資源。這樣一來,頁面和被引用的資源都會使用同一個連接來下載。考慮到建立/關閉 HTTP 連接是一個系統開銷很大的操作,使用同一個連接來下載所有的資源會為web server, client 和 網絡節省很多時間和工作量; 1.2)如何默認使用持久連接:瀏覽器發送如下的請求頭信息: connection: keep-alive
【1.2】塊編碼 1)建立持久連接后,server 可以從多個資源發送字節流,而客戶端也可以使用該連接發送多個請求。這樣的結果就是發送方必須在每個請求或響應中添加 content-length 頭信息。這樣,接收方才知道如何解釋這些字節信息。但發送方通常不知道要發送多少字節,所以必須有一種方法來告訴接收方在不知道發送內容長度的case下,如何解析已經接受到的內容; 2)HTTP1.1 使用一個名為 "transfer-encoding" 的特殊請求頭,來指明字節流將會分塊發送。對每一個塊,塊的長度(以16進制表示)后面會有一個回車/換行符(CR/LF),然后是具體的數據;一個事務以一個長度為0的塊標記。 2.1)看個荔枝:若要用兩個塊發送下面38個字節的內容,其中一塊為29個字節,第2個塊為9個字節:(干貨——塊編碼的一個荔枝) I'm as helpless as a kitten up a tree. 那么實際上應該發送如下內容: 1D\r\n I'm as helpless as a kitten u 9\r\n p a tree. 0\r\n 1D 的10進制表示是29, 表明第一個塊的長度是29個字節,\0\r\n 表明事務已經完成; 【1.3】狀態碼100的使用? 1)使用HTTP1.1的client 可以在向server發送請求體之前發送如下的請求頭,并等待server的確認: Expect: 100-continue //客戶端發送 2)server接收到 “Expect: 100-continue”請求頭后,若它可以接收并處理該請求時,發送如下響應頭: HTTP/1.1 100 continue //注意,返回內容后面要加上 CRLF 字符。然后server 繼續讀取輸入流的內容。
【2】Connector接口(Tomcat的連接器必須實現的接口) 1)該接口中聲明了很多方法,最重要的是 getContainer(), setContainer(), createRequest(), createResponse() 方法;
【3】HttpConnector類(實現了Connector, Runnable, Lifecycle 接口) public final class HttpConnectorimplements Connector, Lifecycle, Runnable { 1)Lifecycle接口:用于維護每個實現了 該接口的每個Catalina組件的生命周期; 2)HttpConnector實現了Lifecycle接口:因此當創建一個 HttpConnector實例后,就應該調用其initialize方法和start方法,在組件的整個生命周期內,這兩個方法只應該被調用一次; public final class Bootstrap {public static void main(String[] args) {HttpConnector connector = new HttpConnector();SimpleContainer container = new SimpleContainer();connector.setContainer(container);try {connector.initialize();connector.start();// make the application wait until we press any key.System.in.read();}catch (Exception e) {e.printStackTrace();}} } 【3.1】創建服務器套接字 1)HttpConnector類的 initialize方法:會調用一個私有方法open(),后者返回一個java.net.ServerSocket實例,賦值給成員變量serverSocket,它是通過open方法從一個服務器套接字工廠得到這個實例; public void initialize() // <span style="font-family: 宋體; font-size: 16px; line-height: 24px;"><strong>HttpConnector.initialize()</strong></span>throws LifecycleException {if (initialized)throw new LifecycleException (sm.getString("httpConnector.alreadyInitialized"));this.initialized=true;Exception eRethrow = null;// Establish a server socket on the specified porttry {serverSocket = open();} catch (IOException ioe) {log("httpConnector, io problem: ", ioe);eRethrow = ioe;} catch (KeyStoreException kse) {log("httpConnector, keystore problem: ", kse);eRethrow = kse;} catch (NoSuchAlgorithmException nsae) {log("httpConnector, keystore algorithm problem: ", nsae);eRethrow = nsae;} catch (CertificateException ce) {log("httpConnector, certificate problem: ", ce);eRethrow = ce;} catch (UnrecoverableKeyException uke) {log("httpConnector, unrecoverable key: ", uke);eRethrow = uke;} catch (KeyManagementException kme) {log("httpConnector, key management problem: ", kme);eRethrow = kme;}if ( eRethrow != null )throw new LifecycleException(threadName + ".open", eRethrow);} private ServerSocket open() // HttpConnector.open()throws IOException, KeyStoreException, NoSuchAlgorithmException,CertificateException, UnrecoverableKeyException,KeyManagementException{// Acquire the server socket factory for this ConnectorServerSocketFactory factory = getFactory();// If no address is specified, open a connection on all addressesif (address == null) {log(sm.getString("httpConnector.allAddresses"));try {return (factory.createSocket(port, acceptCount));} catch (BindException be) {throw new BindException(be.getMessage() + ":" + port);}}// Open a server socket on the specified addresstry {InetAddress is = InetAddress.getByName(address);log(sm.getString("httpConnector.anAddress", address));try {return (factory.createSocket(port, acceptCount, is));} catch (BindException be) {throw new BindException(be.getMessage() + ":" + address +":" + port);}} catch (Exception e) {log(sm.getString("httpConnector.noAddress", address));try {return (factory.createSocket(port, acceptCount));} catch (BindException be) {throw new BindException(be.getMessage() + ":" + port);}}} 【3.2】維護 HttpProcessor 實例 1)在Tomcat默認的連接器中:HttpProcessor實例有一個HttpProcessor 對象池,每個HttpProcessor 實例都運行在其自己的線程中。這樣,HttpConnector實例就可以同時處理多個 HTTP請求了;(干貨——HttpProcessor 對象池就是一個Stack,并不是Vector private Stack processors = new Stack(); // HttpConnector.java void recycle(HttpProcessor processor) { // HttpConnector.java// if (debug >= 2)// log("recycle: Recycling processor " + processor);processors.push(processor);}private HttpProcessor createProcessor() {synchronized (processors) {if (processors.size() > 0) {// if (debug >= 2)// log("createProcessor: Reusing existing processor");return ((HttpProcessor) processors.pop()); // attend for this line.}if ((maxProcessors > 0) && (curProcessors < maxProcessors)) {// if (debug >= 2)// log("createProcessor: Creating new processor");return (newProcessor());} else {if (maxProcessors < 0) {// if (debug >= 2)// log("createProcessor: Creating new processor");return (newProcessor());} else {// if (debug >= 2)// log("createProcessor: Cannot create new processor");return (null);}}}}
補充 Collection體系 |--:List元素是有序的,元素可以重復,因為該集合體系有索引 ? ? |--:ArrayList:底層的數據結構使用的是數組結構,特點:查詢速度很快,但是增刪稍慢,線程不同步 ? ? |--:LinkedList:底層使用的是鏈表數據結構,特點:增刪速度很快,查詢稍慢 ? ? |--:Vector:底層是數組數據結構,線程同步,被ArrayList替代了 |--:Set ?元素是無序的,元素不可以重復 為什么要用 ArrayList 取代 Vector呢??因為, Vector 類的所有方法都是同步的(可以由兩個線程安全的訪問一個 Vector對象);但是, 如果由一個線程訪問 Vector, 代碼需要在同步操作上 耗費大量的時間;(干貨——ArrayList非同步訪問,而Vector同步訪問);而ArryaList 不是同步 的, 所以, 建議在不需要同步時 使用 ArrayList, 而不要使用 Vector; 補充over
2)在HttpConnector中:創建的HttpProcessor 實例的個數由兩個變量決定:minProcessors 和 maxProcessors; 2.1)初始,HttpConnector對象會依據minProcessors的數值來創建?HttpProcessor實例:若是請求的數目超過了HttpProcessor 實例所能處理的范圍,HttpConnector 實例就會創建更多的HttpProcessor實例,直到數目達到 ?maxProcessors 限定的范圍; 2.2)若希望可以持續地創建 HttpProcessor實例: 就可以將?maxProcessors 設定為負值; 2.3)看個代碼:下面的代碼是在 HttpConnector 類中的start方法中創建初始數量的 HTTPProcessor實例的部分實現:(干貨——HttpConnector.start方法調用了HttpConnector.newProcessor方法,而HttpConnector.newProcessor方法調用了HttpProcessor.start方法) public void start() throws LifecycleException { // HttpConnector.start()// Validate and update our current stateif (started)throw new LifecycleException(sm.getString("httpConnector.alreadyStarted"));threadName = "HttpConnector[" + port + "]";lifecycle.fireLifecycleEvent(START_EVENT, null);started = true;// Start our background threadthreadStart(); // invoke run method.// Create the specified minimum number of processorswhile (curProcessors < minProcessors) {if ((maxProcessors > 0) && (curProcessors >= maxProcessors))break;HttpProcessor processor = newProcessor();recycle(processor);}} private HttpProcessor newProcessor() { // H<span style="font-family: 宋體;">ttpConnector.newProcessor()</span>// if (debug >= 2)// log("newProcessor: Creating new processor");HttpProcessor processor = new HttpProcessor(this, curProcessors++);if (processor instanceof Lifecycle) {try {((Lifecycle) processor).start();} catch (LifecycleException e) {log("newProcessor", e);return (null);}}created.addElement(processor); // created is a Vector Collection.return (processor);} private Vector created = new Vector(); void recycle(HttpProcessor processor) { // HttpContainer.recycle()// if (debug >= 2)// log("recycle: Recycling processor " + processor);processors.push(processor);} public void stop() throws LifecycleException {// Validate and update our current stateif (!started)throw new LifecycleException(sm.getString("httpConnector.notStarted"));lifecycle.fireLifecycleEvent(STOP_EVENT, null);started = false;// Gracefully shut down all processors we have createdfor (int i = created.size() - 1; i >= 0; i--) {HttpProcessor processor = (HttpProcessor) created.elementAt(i); // this line.if (processor instanceof Lifecycle) {try {((Lifecycle) processor).stop();} catch (LifecycleException e) {log("HttpConnector.stop", e);}}}synchronized (threadSync) {// Close the server socket we were usingif (serverSocket != null) {try {serverSocket.close();} catch (IOException e) {;}}// Stop our background threadthreadStop();}serverSocket = null;} Attention) A0)顯然變量created是private類型:其在HttpConnector.java 中出現了3次,一次是?private Vector created = new Vector();, 一次是created.addElement(processor);還有一次是stop方法中(上述最后一段代碼)(干貨——但,HttpProcessor的對象池不是Vector而是Stack) A1)其中,newProcessor方法負責創建 HttpProcessor 實例,并將 curProcessors 加1;recycle() 方法將創建的HttpProcessor 對象入棧; A2)每個 HttpProcessor 實例負責解析HTTP請求行和請求頭, 填充 request對象; void recycle(HttpProcessor processor) { // // if (debug >= 2)// log("recycle: Recycling processor " + processor);processors.push(processor); // <span style="font-weight: bold; font-family: 宋體;">processors is a stack.</span>} private Stack processors = new Stack(); // HttpConnector.java 【3.3】提供HTTP請求服務 1)HttpConnector類的主要業務邏輯在其run() 方法中。run() 方法包含一個 while循環,在該循環體內,服務器套接字等待 HTTP請求,直到HttpConnector對象關閉; public void run() { // HttpConnector.run()// Loop until we receive a shutdown commandwhile (!stopped) {// Accept the next incoming connection from the server socketSocket socket = null;try {// if (debug >= 3)// log("run: Waiting on serverSocket.accept()");socket = serverSocket.accept();// if (debug >= 3)// log("run: Returned from serverSocket.accept()");if (connectionTimeout > 0)socket.setSoTimeout(connectionTimeout);socket.setTcpNoDelay(tcpNoDelay);} catch (AccessControlException ace) {log("socket accept security exception", ace);continue;} catch (IOException e) {// if (debug >= 3)// log("run: Accept returned IOException", e);try {// If reopening fails, exitsynchronized (threadSync) {if (started && !stopped)log("accept error: ", e);if (!stopped) {// if (debug >= 3)// log("run: Closing server socket");serverSocket.close();// if (debug >= 3)// log("run: Reopening server socket");serverSocket = open();}}// if (debug >= 3)// log("run: IOException processing completed");} catch (IOException ioe) {log("socket reopen, io problem: ", ioe);break;} catch (KeyStoreException kse) {log("socket reopen, keystore problem: ", kse);break;} catch (NoSuchAlgorithmException nsae) {log("socket reopen, keystore algorithm problem: ", nsae);break;} catch (CertificateException ce) {log("socket reopen, certificate problem: ", ce);break;} catch (UnrecoverableKeyException uke) {log("socket reopen, unrecoverable key: ", uke);break;} catch (KeyManagementException kme) {log("socket reopen, key management problem: ", kme);break;}continue;}// Hand this socket off to an appropriate processorHttpProcessor processor = createProcessor();if (processor == null) {try {log(sm.getString("httpConnector.noProcessor"));socket.close();} catch (IOException e) {;}continue;}// if (debug >= 3)// log("run: Assigning socket to processor " + processor);processor.assign(socket);// The processor will recycle itself when it finishes}// Notify the threadStop() method that we have shut ourselves down// if (debug >= 3)// log("run: Notifying threadStop() that we have shut down");synchronized (threadSync) {threadSync.notifyAll();}} 2)對于每個引入的HTTP請求,它通過 調用其私有方法 createProcessor() 獲得一個HttpProcessor對象; HttpProcessor processor = createProcessor(); // invoked by HttpContainer.run() method. private Stack processors = new Stack(); // you should know the processors is a Stack. private HttpProcessor createProcessor() { // HttpConnector.createProcessor() synchronized (processors) {if (processors.size() > 0) {// if (debug >= 2)// log("createProcessor: Reusing existing processor");return ((HttpProcessor) processors.pop());}if ((maxProcessors > 0) && (curProcessors < maxProcessors)) {// if (debug >= 2)// log("createProcessor: Creating new processor");return (newProcessor());} else {if (maxProcessors < 0) {// if (debug >= 2)// log("createProcessor: Creating new processor");return (newProcessor());} else {// if (debug >= 2)// log("createProcessor: Cannot create new processor");return (null);}}}}<span style="font-family: 宋體;"> </span>
3)若createProcessor() 方法的返回值不是null,則會將客戶端套接字傳入到 HttpProcessor類的 assign()方法中: // Hand this socket off to an appropriate processorHttpProcessor processor = createProcessor(); // these code are located in HttpConnector.run() if (processor == null) {try {log(sm.getString("httpConnector.noProcessor"));socket.close();} catch (IOException e) {;}continue;}// if (debug >= 3)// log("run: Assigning socket to processor " + processor);processor.assign(socket); // this line, invoked by HttpConnector.run method.// The processor will recycle itself when it finishes}// Notify the threadStop() method that we have shut ourselves down// if (debug >= 3)// log("run: Notifying threadStop() that we have shut down");synchronized (threadSync) {threadSync.notifyAll();} synchronized void assign(Socket socket) {// Wait for the Processor to get the previous Socketwhile (available) {try {wait();} catch (InterruptedException e) {}}// Store the newly available Socket and notify our threadthis.socket = socket;available = true;notifyAll();if ((debug >= 1) && (socket != null))log(" An incoming request is being assigned");} 4)現在,HttpProcessor實例的任務是讀取套接字的輸入流,解析HTTP請求。這里需要注意的是,assign方法直接返回,而不需要等待?HttpProcessor 實例完成解析,這樣 HttpContainer才能持續服務傳入的 HTTP請求,而 HttpProcessor 實例是在其自己的線程中完成解析工作的;
【4】HttpProcessor類(主要講解該類的assign方法的異步實現) 0)HttpProcessor類中另一個重要的方法是其私有方法process() 方法:該方法負責解析 HTTP請求,并調用相應的servlet容器的invoke方法; private void process(Socket socket) {boolean ok = true;boolean finishResponse = true;SocketInputStream input = null;OutputStream output = null;// Construct and initialize the objects we will needtry {input = new SocketInputStream(socket.getInputStream(),connector.getBufferSize());} catch (Exception e) {log("process.create", e);ok = false;}keepAlive = true;while (!stopped && ok && keepAlive) {finishResponse = true;try {request.setStream(input);request.setResponse(response);output = socket.getOutputStream();response.setStream(output);response.setRequest(request);((HttpServletResponse) response.getResponse()).setHeader("Server", SERVER_INFO);} catch (Exception e) {log("process.create", e);ok = false;}// Parse the incoming requesttry {if (ok) {parseConnection(socket);parseRequest(input, output);if (!request.getRequest().getProtocol().startsWith("HTTP/0"))parseHeaders(input);if (http11) {// Sending a request acknowledge back to the client if// requested.ackRequest(output);// If the protocol is HTTP/1.1, chunking is allowed.if (connector.isChunkingAllowed())response.setAllowChunking(true);}}} catch (EOFException e) {// It's very likely to be a socket disconnect on either the // client or the serverok = false;finishResponse = false;} catch (ServletException e) {ok = false;try {((HttpServletResponse) response.getResponse()).sendError(HttpServletResponse.SC_BAD_REQUEST);} catch (Exception f) {;}} catch (InterruptedIOException e) {if (debug > 1) {try {log("process.parse", e);((HttpServletResponse) response.getResponse()).sendError(HttpServletResponse.SC_BAD_REQUEST);} catch (Exception f) {;}}ok = false;} catch (Exception e) {try {log("process.parse", e);((HttpServletResponse) response.getResponse()).sendError(HttpServletResponse.SC_BAD_REQUEST);} catch (Exception f) {;}ok = false;}// Ask our Container to process this requesttry {((HttpServletResponse) response).setHeader("Date", FastHttpDateFormat.getCurrentDate());if (ok) {connector.getContainer().invoke(request, response); // process method invokes the invoke method of corresponding servlet container}} catch (ServletException e) {log("process.invoke", e);try {((HttpServletResponse) response.getResponse()).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);} catch (Exception f) {;}ok = false;} catch (InterruptedIOException e) {ok = false;} catch (Throwable e) {log("process.invoke", e);try {((HttpServletResponse) response.getResponse()).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);} catch (Exception f) {;}ok = false;}// Finish up the handling of the requestif (finishResponse) {try {response.finishResponse();} catch (IOException e) {ok = false;} catch (Throwable e) {log("process.invoke", e);ok = false;}try {request.finishRequest();} catch (IOException e) {ok = false;} catch (Throwable e) {log("process.invoke", e);ok = false;}try {if (output != null)output.flush();} catch (IOException e) {ok = false;}}// We have to check if the connection closure has been requested// by the application or the response stream (in case of HTTP/1.0// and keep-alive).if ( "close".equals(response.getHeader("Connection")) ) {keepAlive = false;}// End of request processingstatus = Constants.PROCESSOR_IDLE;// Recycling the request and the response objectsrequest.recycle();response.recycle();}try {shutdownInput(input);socket.close();} catch (IOException e) {;} catch (Throwable e) {log("process.invoke", e);}socket = null;} 1)在Tomcat的默認連接器中,HttpProcessor類實現了 java.lang.Runnable 接:這樣,每個HttpProcessor實例就可以運行在自己的線程中了,稱為“處理器線程”。為每個?HttpProcessor 對象創建?HttpProcessor 實例后,會調用其start方法,啟動HttpProcessor 實例的處理器線程;(下面是?HttpProcessor類中的run方法的實現)(干貨——注意區分開HttpProcessor.run方法和 HttpConnector.run方法 ) public void run() { // HttpProcessor.run()// Process requests until we receive a shutdown signalwhile (!stopped) {// Wait for the next socket to be assignedSocket socket = await(); // this line, <span style="font-family: 宋體; font-size: 16px; line-height: 24px;">run方法的while循環執行到 await方法時會阻塞</span>if (socket == null)continue;// Process the request from this sockettry {process(socket);} catch (Throwable t) {log("process.invoke", t);}// Finish up this requestconnector.recycle(this);}// Tell threadStop() we have shut ourselves down successfullysynchronized (threadSync) {threadSync.notifyAll();}} private synchronized Socket await() { // HttpProcessor.await()// Wait for the Connector to provide a new Socketwhile (!available) {try {wait();} catch (InterruptedException e) {}}// Notify the Connector that we have received this SocketSocket socket = this.socket;available = false;notifyAll();if ((debug >= 1) && (socket != null))log(" The incoming request has been awaited");return (socket);} 對以上代碼的分析(Analysis): A1)run方法中的while循環做如下幾件事情:獲取套接字對象,進行處理,調用連接器的recycle() 方法將當前的 HttpRequest實例壓回棧中。 A2)下面是 HttpConnector類中 recycle方法的代碼:? */void recycle(HttpProcessor processor) {// if (debug >= 2)// log("recycle: Recycling processor " + processor);processors.push(processor);} A3)run方法的while循環執行到 await方法時會阻塞。await方法會阻塞處理器線程的控制流,直到它從HttpConnector中獲得了新的Socket對象。即,直到HttpConnector對象調用 HttpProcessor實例的assign方法前,都會一直阻塞; 但是,await方法 和assign方法并不是運行在同一個線程中的。assign方法是從 HttpConnector對象的 run方法中調用的。我們稱 HttpConnector實例中run方法運行時所在的線程為“連接器線程”。通過使用available的布爾變量和 Object.wait() 方法 和 notifyAll() 方法來進行溝通的; /*** Await a newly assigned Socket from our Connector, or <code>null</code>* if we are supposed to shut down.*/private synchronized Socket await() {// Wait for the Connector to provide a new Socketwhile (!available) {try {wait();} catch (InterruptedException e) {}}// Notify the Connector that we have received this SocketSocket socket = this.socket;available = false;notifyAll();if ((debug >= 1) && (socket != null))log(" The incoming request has been awaited");return (socket);} Attention) A1)wait方法會使當前線程進入等待狀態,直到其他線程調用了這個對象的notify() 方法和notifyAll方法; A2)下表總結了 await方法和 assign方法的程序流;
Why) W1)為什么 await方法要使用一個局部變量 socket,而不直接將成員變量socket返回呢? 因為使用局部變量可以在當前Socket對象處理完之前,繼續接收下一個Socket對象; W2)為什么 await方法需要調用notifyAll方法呢?是為了防止出現另一個Socket對象以及到達,而此時變量available的值還是true的case。在這種case下,連接器線程會在assign方法內的循環中阻塞,知道處理器線程調用了 notifyAll方法;
【5】Request對象(繼承了 RequestBase) 【6】Response對象 【7】處理請求(重點討論 HttpProcessor類的 process方法) 1)process方法執行以下3個操作: 解析連接, 解析請求, 解析請求頭 2)intro to process method: 2.1)通過在Connector接口中設置緩沖區的大小,任何人都可以使用連接器來設置緩沖區的大小; private void process(Socket socket) { // HttpProcessor.process()boolean ok = true;boolean finishResponse = true;SocketInputStream input = null;OutputStream output = null;// Construct and initialize the objects we will needtry {input = new SocketInputStream(socket.getInputStream(),connector.getBufferSize());} catch (Exception e) {log("process.create", e);ok = false;}keepAlive = true;while (!stopped && ok && keepAlive) {finishResponse = true;try {request.setStream(input);request.setResponse(response);output = socket.getOutputStream();response.setStream(output);response.setRequest(request);((HttpServletResponse) response.getResponse()).setHeader("Server", SERVER_INFO);} catch (Exception e) {log("process.create", e);ok = false;}// Parse the incoming requesttry {if (ok) {parseConnection(socket); // step1:解析連接parseRequest(input, output); // step2:解析請求if (!request.getRequest().getProtocol() .startsWith("HTTP/0"))parseHeaders(input); // step3:解析請求頭if (http11) {// Sending a request acknowledge back to the client if// requested.ackRequest(output);// If the protocol is HTTP/1.1, chunking is allowed.if (connector.isChunkingAllowed())response.setAllowChunking(true);}}} catch (EOFException e) {// It's very likely to be a socket disconnect on either the // client or the serverok = false;finishResponse = false;} catch (ServletException e) {ok = false;try {((HttpServletResponse) response.getResponse()).sendError(HttpServletResponse.SC_BAD_REQUEST);} catch (Exception f) {;}} catch (InterruptedIOException e) {if (debug > 1) {try {log("process.parse", e);((HttpServletResponse) response.getResponse()).sendError(HttpServletResponse.SC_BAD_REQUEST);} catch (Exception f) {;}}ok = false;} catch (Exception e) {try {log("process.parse", e);((HttpServletResponse) response.getResponse()).sendError(HttpServletResponse.SC_BAD_REQUEST);} catch (Exception f) {;}ok = false;}// Ask our Container to process this requesttry {((HttpServletResponse) response).setHeader("Date", FastHttpDateFormat.getCurrentDate());if (ok) {connector.getContainer().invoke(request, response);}} catch (ServletException e) {log("process.invoke", e);try {((HttpServletResponse) response.getResponse()).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);} catch (Exception f) {;}ok = false;} catch (InterruptedIOException e) {ok = false;} catch (Throwable e) {log("process.invoke", e);try {((HttpServletResponse) response.getResponse()).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);} catch (Exception f) {;}ok = false;}// Finish up the handling of the requestif (finishResponse) {try {response.finishResponse();} catch (IOException e) {ok = false;} catch (Throwable e) {log("process.invoke", e);ok = false;}try {request.finishRequest();} catch (IOException e) {ok = false;} catch (Throwable e) {log("process.invoke", e);ok = false;}try {if (output != null)output.flush();} catch (IOException e) {ok = false;}}// We have to check if the connection closure has been requested// by the application or the response stream (in case of HTTP/1.0// and keep-alive).if ( "close".equals(response.getHeader("Connection")) ) {keepAlive = false;}// End of request processingstatus = Constants.PROCESSOR_IDLE;// Recycling the request and the response objectsrequest.recycle();response.recycle();}try {shutdownInput(input);socket.close();} catch (IOException e) {;} catch (Throwable e) {log("process.invoke", e);}socket = null;} 2.2)然后是while循環,在該循環內,不斷讀入輸入流,知道HttpProcessor 實例終止,拋出一個異常,或連接斷開; // Parse the incoming requesttry { // there code are located in HttpProcessor.process() method.if (ok) {parseConnection(socket);parseRequest(input, output);if (!request.getRequest().getProtocol().startsWith("HTTP/0"))parseHeaders(input);if (http11) {// Sending a request acknowledge back to the client if// requested.ackRequest(output);// If the protocol is HTTP/1.1, chunking is allowed.if (connector.isChunkingAllowed())response.setAllowChunking(true);}}} 【7.1】解析連接 1)parseConnection() 方法:會從套接字中獲取Internet地址,將其賦值給 HttpRequestImpl 對象;此外,它還要檢查是否使用了代理,將Socket對象賦值給 request對象; private void parseConnection(Socket socket) // HttpProcessor.parseConnection()throws IOException, ServletException {if (debug >= 2)log(" parseConnection: address=" + socket.getInetAddress() +", port=" + connector.getPort());((HttpRequestImpl) request).setInet(socket.getInetAddress());if (proxyPort != 0)request.setServerPort(proxyPort);elserequest.setServerPort(serverPort);request.setSocket(socket);} 【7.2】解析請求 【7.3】解析請求頭 1)默認連接器中的parseHeaders() 方法:使用了 org.apache.catalina.connector.http 包內的HttpHeader類和 DefaultHeader類。HttpHeader類表示一個HTTP 請求頭。HttpHeader 類使用了字符數組來避免高代價的字符串操作。DefaultHeaders類是一個final類,包含了 字符數組形式的標準HTTP請求頭: final class DefaultHeaders {// -------------------------------------------------------------- Constantsstatic final char[] AUTHORIZATION_NAME = "authorization".toCharArray();static final char[] ACCEPT_LANGUAGE_NAME = "accept-language".toCharArray();static final char[] COOKIE_NAME = "cookie".toCharArray();static final char[] CONTENT_LENGTH_NAME = "content-length".toCharArray();static final char[] CONTENT_TYPE_NAME = "content-type".toCharArray();static final char[] HOST_NAME = "host".toCharArray();static final char[] CONNECTION_NAME = "connection".toCharArray();static final char[] CONNECTION_CLOSE_VALUE = "close".toCharArray();static final char[] EXPECT_NAME = "expect".toCharArray();static final char[] EXPECT_100_VALUE = "100-continue".toCharArray();static final char[] TRANSFER_ENCODING_NAME ="transfer-encoding".toCharArray();static final HttpHeader CONNECTION_CLOSE =new HttpHeader("connection", "close");static final HttpHeader EXPECT_CONTINUE =new HttpHeader("expect", "100-continue");static final HttpHeader TRANSFER_ENCODING_CHUNKED =new HttpHeader("transfer-encoding", "chunked"); 2)parseHeaders() 方法使用while循環讀取所有的HTTP 請求信息。調用request對象的 allocateHeader方法獲取一個內容為空的 HttpHeader實例開始。然后該實例被傳入SocketInputStream 實例的readHeader方法中: private void parseHeaders(SocketInputStream input) // HttpProcessor.parseHeaders()throws IOException, ServletException {while (true) {HttpHeader header = request.allocateHeader();// Read the next headerinput.readHeader(header);if (header.nameEnd == 0) {if (header.valueEnd == 0) {return;} else {throw new ServletException(sm.getString("httpProcessor.parseHeaders.colon"));}}String value = new String(header.value, 0, header.valueEnd);if (debug >= 1)log(" Header " + new String(header.name, 0, header.nameEnd)+ " = " + value);......request.nextHeader();}} 3)若所有的請求頭都已經讀取過了,則readHeader()方法不會再給 HttpHeader 實例設置name屬性了。就退出parseHeader方法了: if (header.nameEnd == 0) {if (header.valueEnd == 0) {return;} else {throw new ServletException(sm.getString("httpProcessor.parseHeaders.colon"));}} 【8】簡單的Container 應用程序 1)SimpleContainer類實現了 org.apache.catalina.Container接口,這樣它就可以與默認連接器進行關聯。? public class SimpleContainer implements Container { // just demonstrate a core method invoke.public void invoke(Request request, Response response)throws IOException, ServletException {String servletName = ( (HttpServletRequest) request).getRequestURI();servletName = servletName.substring(servletName.lastIndexOf("/") + 1);URLClassLoader loader = null;try {URL[] urls = new URL[1];URLStreamHandler streamHandler = null;File classPath = new File(WEB_ROOT);String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString() ;urls[0] = new URL(null, repository, streamHandler);loader = new URLClassLoader(urls);}catch (IOException e) {System.out.println(e.toString() );}Class myClass = null;try {myClass = loader.loadClass("servlet." + servletName);}catch (ClassNotFoundException e) {System.out.println(e.toString());}Servlet servlet = null;try {servlet = (Servlet) myClass.newInstance();servlet.service((HttpServletRequest) request, (HttpServletResponse) response);}catch (Exception e) {System.out.println(e.toString());}catch (Throwable e) {System.out.println(e.toString());}} Attention)我總結了一張Tomcat默認連接器測試用例的大致調用過程
/*** Await a newly assigned Socket from our Connector, or <code>null</code>* if we are supposed to shut down.*/private synchronized Socket await() { //HttpProcessor.awati() 方法// Wait for the Connector to provide a new Socketwhile (!available) {try {wait();} catch (InterruptedException e) {}}// Notify the Connector that we have received this SocketSocket socket = this.socket;available = false;notifyAll();if ((debug >= 1) && (socket != null))log(" The incoming request has been awaited");return (socket);} 對以上代碼的分析(Analysis): A1)HttpConnector類的大致工作: step1)initialize方法:調用該類的open方法創建服務器套接字; step2)start方法:開啟一個線程,該線程中有一個while循環,不斷接收client發送的HTTP連接請求,接著調用其類的createProcessor方法; step3)createProcessor方法:調用其類的 newProcessor方法; step4)newProcessor方法:創建HttpProcessor(HTTP連接器的支持類,HTTP請求處理器),利用HttpProcessor實例開啟一個線程,調用 HttpProcessor.run()方法;(轉向HttpProcessor類的run方法)(干貨中的干貨——也即當clients 發出http 連接請求后,HttpConnector 在while循環中創建HttpConnector的支持類 HttpProcessor,Http處理器類,并調用該類的start方法,開啟線程,即while循環為每一個client 請求 開啟一個線程進行處理,多么巧妙) A2)HttpProcessor類的大致工作: step1)run方法:傳入套接字參數,并調用process方法; step2)process方法:依次調用 parseConnection()方法, parseRequest()方法, parseHeader() 方法: 上述3個方法的作用參見本文章節【7】(也可以參見下面的補充);調用上述三個方法后,會調用連接器HttpConnector實例的關聯容器的invoke方法;(轉向container的invoke方法) step3)SimleContainer.invoke方法:invoke方法聲明為,invoke(Request request, Response response):(見下面的代碼實例) step3.1)創建類加載器; step3.2)利用類加載器集合request中的請求URI(HttpProcessor.parseReqeust解析出的請求URI),加載請求的servlet,創建該servlet實例并調用其service方法(service方法接著就會向client發送響應信息),ending; public final class Bootstrap {public static void main(String[] args) {HttpConnector connector = new HttpConnector();SimpleContainer container = new SimpleContainer(); // 創建容器connector.setContainer(container); // 將該 容器 和 http連接器 相關聯try {connector.initialize();connector.start();// make the application wait until we press any key.System.in.read();}catch (Exception e) {e.printStackTrace();}} }
補充-Complementary begins) C1)HttpProcessor.parseConnection方法:會從套接字中獲取internet地址,端口號,協議等信息; C2)HttpProcessor.parseRequest方法:會解析請求體的第一行請求信息(請求方法——URI——協議/版本); C3)HttpProcessor.parseHeader方法:解析請求體中的請求頭信息,還會附加解析cookie信息; 補充-Complementary ends)

補充-Complementary2 begins)在補充一個知識點(request和response是何時創建的?——其實在HttpProcessor 構造器中就已經創建了) public HttpProcessor(HttpConnector connector, int id) {super();this.connector = connector;this.debug = connector.getDebug();this.id = id;this.proxyName = connector.getProxyName();this.proxyPort = connector.getProxyPort();this.request = (HttpRequestImpl) connector.createRequest();this.response = (HttpResponseImpl) connector.createResponse();this.serverPort = connector.getPort();this.threadName ="HttpProcessor[" + connector.getPort() + "][" + id + "]";} public Request createRequest() { HttpRequestImpl request = new HttpRequestImpl();request.setConnector(this);return (request);}public Response createResponse() {HttpResponseImpl response = new HttpResponseImpl();response.setConnector(this);return (response);}補充-Complementary2 ends)
【9】運行應用程序 9.1)運行參數 E:\bench-cluster\cloud-data-preprocess\HowTomcatWorks\src>java -cp .;lib/servlet.jar;lib/catalina_4_1_24.jar;E:\bench-cluster\cloud-data-preprocess\HowTomcatWorks\webroot com.tomcat.chapter4.startup.Bootstrap HttpConnector Opening server socket on all host IP addresses HttpConnector[8080] Starting background thread from service from service 9.2)運行結果

總結

以上是生活随笔為你收集整理的tomcat(4)Tomcat的默认连接器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。