Tomcat學習筆記(一)一個簡單的Web伺服器,tomcat學習筆記
內容為《深入剖析Tomcat》第一章重點,以及自己的總結,如有描述不清的,可查看原書。一、HTTP協議:1、定義:用於伺服器與用戶端的通訊的協議,允許web伺服器和瀏覽器通過互連網進行發送和接收資料。是一種請求和響應協議,使用可靠的TCP協議,TCP協議的連接埠為80,是一種連線導向的協議。2、HTTP協議請求的三個組成部分:這三部分之間用斷行符號分行符號(CRLF)隔開 請求部分:方法(GET/POST等7種,其他的很少用,書上有介紹)[空格,該部分內容以空格隔開] 統一資源識別項URI[空格,該部分內容以空格隔開 ] 協議/協議版本 URL通常都是相對伺服器的根目錄,因此以“/”開頭。 要求標頭部:請求的頭部包含了關於用戶端環境和請求的主體內容的有用資訊。例如它可能包括瀏覽器設定的語言,主體內容的長度等等。每個頭部通過一個斷行符號分行符號(CRLF)來分隔的。 請求主體內容:對於HTTP請求格式來說,頭部和主體內容之間有一個斷行符號分行符號(CRLF)是相當重要的。CRLF告訴HTTP伺服器主體內容是在什麼地方開始的。在一些互連網編程書籍中,CRLF還被認為是HTTP請求的第四部分。3、 HTTP響應也包括三個部分: · 方法—統一資源識別項(URI)—協議/版本· 響應的頭部· 主體內容 二、伺服器與用戶端通訊1、伺服器與用戶端通訊需要用到兩個部分:Socket(用戶端)和ServerSocket(伺服器端)(1)ServerSocket(java.net.ServerSocket, 伺服器端通訊端),要建立一個伺服器通訊端,你需要使用ServerSocket類提供的四個構造方法中的一個。你需要指定IP地址和伺服器通訊端將要進行監聽的連接埠號碼。通常,IP地址將會是127.0.0.1,也就是說,伺服器通訊端將會監聽本地機器。伺服器通訊端正在監聽的IP地址被稱為是綁定地址。伺服器通訊端的另一個重要的屬性是backlog,這是伺服器通訊端開始拒絕傳入的請求之前,傳入的串連請求的最大隊列長度,四種構造方法分別為: ServerSocket ss = new ServerSocket();//建立一個未綁定的ServerSocket ServerSocket ss = new ServerSocket(int port);//建立一個綁定到某連接埠的ServerSocket ServerSocket ss = new ServerSocket(int port, int log);//建立一個綁定到某連接埠的ServerSocket,並設定了最大隊列長度。 ServerSocket ss = new ServerSocket(int port, int log, InetAddress address);//建立一個綁定到某地址、某連接埠的ServerSocket,並設定了最大隊列長度。 對於第四個構造方法,綁定地址必須是InetAddress的一個執行個體,一種構造InetAddress對象的簡單的方法是調用它的靜態方法getByName,傳入一個包含主機名稱的字串,就像下面的代碼一樣。 InetAddress.getByName("127.0.0.1"); 建立ServerSocket的常用方法: new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1")); 代碼構造了一個監聽本地機器8080連接埠的ServletSocket,它的隊列長度為1. 伺服器建立後就保持等待狀態(TCP協議,可靠的傳輸協議,是同步協議,即沒有響應返回就一直等待)(2)Socket(java.net.Socket類,用戶端通訊端):需要知道要訪問的伺服器端的IP/主機名稱和連接埠號碼,即可向伺服器端發送請求。可以用Socket的眾多構造方法中的一個來建立Socket new Socket ("yahoo.com", 80); 一旦你成功建立了一個Socket類的執行個體,你可以使用它來發送和接受位元組流。要發送位元組流,你首先必須調用Socket類的getOutputStream方法來擷取一個java.io.OutputStream對象。要發送文本到一個遠程應用,你經常要從返回的OutputStream對象中構造一個java.io.PrintWriter對象。要從串連的另一端接受位元組流,你可以調用Socket類的getInputStream方法用來返回一個java.io.InputStream對象。 (3)伺服器端通過accept()方法來接收用戶端的串連請求,並與用戶端建立串連,同時返回一個Socket Socket s = ss. accept();(4)通過Socket可以獲得一個輸入資料流和一個輸出資料流, 輸入資料流用於讀取用戶端請求資料,輸出資料流用於向用戶端返迴響應資訊。比如:InputStream input = s.getInputStream(); OutputStream output = s.getOutputStream();三、簡單的Web伺服器通訊樣本(建議拷貝到MyEclipse來看並執行)1、伺服器類
package com.socket.httpservertest;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;public class HttpServer { public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot"; // shutdown command private static final String SHUTDOWN_COMMAND = "/SHUTDOWN"; // the shutdown command received private boolean shutdown = false; public static void main(String[] args) { HttpServer server = new HttpServer(); server.await(); } public void await() { // System.out.println(System.getProperty("user.dir")); ServerSocket serverSocket = null; int port = 8080; try { serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1")); } catch (IOException e) { e.printStackTrace(); System.exit(1); } while (!shutdown) { Socket socket = null; InputStream input = null; OutputStream output = null; try { //接收了用戶端發來的請求,否則一致是等待狀態 socket = serverSocket.accept(); input = socket.getInputStream(); output = socket.getOutputStream(); // create Request object and parse Request request = new Request(input); request.parse(); //從請求中讀取內容 // create Response object Response response = new Response(output); response.setRequest(request); response.sendStaticResource(); // Close the socket socket.close(); //check if the previous URI is a shutdown command shutdown = request.getUri().equals(SHUTDOWN_COMMAND); }catch (Exception e) { e.printStackTrace (); continue; } } }}2、請求類
package com.socket.httpservertest;import java.io.IOException;import java.io.InputStream;public class Request { private InputStream input; private String uri; public Request(InputStream input) { this.input = input; } public void parse() { // Read a set of characters from the socket StringBuffer request = new StringBuffer(2048); int i; byte[] buffer = new byte[2048]; try { i = input.read(buffer); //將從輸入資料流取2048長度的內容存到buffer位元組數組中,如果內容不到2048,數組其他空間剩餘空著 } catch (IOException e) { e.printStackTrace(); i = -1; } for (int j=0; j<i; j++) { request.append((char) buffer[j]); } System.out.print(request.toString()); uri = parseUri(request.toString()); } private String parseUri(String requestString) { int index1, index2; index1 = requestString.indexOf(' '); /* * http請求行的結構:方法 統一資源識別項(URI) 協議/版本(它們之間以空格分隔) * 例如:POST //examples/default.jsp HTTP/1.1 */ if (index1 != -1) {// index1 == -1表示沒找到 index2 = requestString.indexOf(' ', index1 + 1);//從index+1位置開始尋找‘ ’ if (index2 > index1) return requestString.substring(index1 + 1, index2); } return null; } public String getUri() { return uri; }}3、響應類
package com.socket.httpservertest;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;public class Response { private static final int BUFFER_SIZE = 1024; Request request; OutputStream output; public Response(OutputStream output) { this.output = output; } public void setRequest(Request request) { this.request = request; } public void sendStaticResource() throws IOException { byte[] bytes = new byte[BUFFER_SIZE]; FileInputStream fis = null; try { File file = new File(HttpServer.WEB_ROOT, request.getUri()); if (file.exists()) { fis = new FileInputStream(file); int ch = fis.read(bytes, 0, BUFFER_SIZE); while (ch!=-1) { //ch==-1表示讀到末尾了 output.write(bytes, 0, ch); //寫出到瀏覽器 ch = fis.read(bytes, 0, BUFFER_SIZE);//再讀會接上一次讀的位置往下讀,如果讀到末尾就會返回-1,終止輸出 } } else { // file not found String errorMessage = "HTTP/1.1 404 File Not Found\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 23\r\n" + "\r\n" + "<h1>File Not Found</h1>"; output.write(errorMessage.getBytes()); } }catch (Exception e) { // thrown if cannot instantiate a File object System.out.println(e.toString() ); } finally { if (fis!=null) fis.close(); } }}4、範例程式碼功能描述:瀏覽器輸入http請求,比如http://localhost:8080/MyHtml.html;伺服器接收請求後用輸入資料流讀取請求內容獲得檔案位置,再用檔案輸入資料流讀取檔案中的內容;最後給瀏覽器用戶端返迴響應,把html檔案中的內容顯示在瀏覽器上, 5、範例程式碼跨職能流程圖: