天天看點

Tomcat源碼分析 (一)----- 手寫一個web伺服器

作為後端開發人員,在實際的工作中我們會非常高頻地使用到web伺服器。而tomcat作為web伺服器領域中舉足輕重的一個web架構,又是不能不學習和了解的。

tomcat其實是一個web架構,那麼其内部是怎麼實作的呢?如果不用tomcat我們能自己實作一個web伺服器嗎?

首先,tomcat内部的實作是非常複雜的,也有非常多的各類元件,我們在後續章節會深入地了解。

其次,本章我們将自己實作一個web伺服器的。

下面我們就自己來實作一個看看。(【注】:參考了《How tomcat works》這本書)

http協定簡介

http是一種協定(超文本傳輸協定),允許web伺服器和浏覽器通過Internet來發送和接受資料,是一種請求/響應協定。http底層使用TCP來進行通信。目前,http已經疊代到了2.x版本,從最初的0.9、1.0、1.1到現在的2.x,每個疊代都加了很多功能。

在http中,始終都是用戶端發起一個請求,伺服器接受到請求之後,然後處理邏輯,處理完成之後再發送響應資料,用戶端收到響應資料,然後請求結束。在這個過程中,用戶端和伺服器都可以對建立的連接配接進行中斷操作。比如可以通過浏覽器的停止按鈕。

http協定-請求

一個http協定的請求包含三部分:

  1. 方法 URI 協定/版本
  2. 請求的頭部
  3. 主體内容

舉個例子

POST /examples/default.jsp HTTP/1.1
Accept: text/plain; text/html
Accept-Language: en-gb
Connection: Keep-Alive
Host: localhost
User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)
Content-Length: 33
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate

lastName=Franks&firstName=Michael      

資料的第一行包括:方法、URI、協定和版本。在這個例子裡,方法為

POST

,URI為

/examples/default.jsp

,協定為

HTTP/1.1

,協定版本号為

1.1

。他們之間通過空格來分離。

請求頭部從第二行開始,使用英文冒号(:)來分離鍵和值。

請求頭部和主體内容之間通過空行來分離,例子中的請求體為表單資料。

http協定-響應

類似于http協定的請求,響應也包含三個部分。

  1. 協定 狀态 狀态描述
  2. 響應的頭部
  3. 主體内容

舉個例子

HTTP/1.1 200 OK
Server: Microsoft-IIS/4.0
Date: Mon, 5 Jan 2004 13:13:33 GMT
Content-Type: text/html
Last-Modified: Mon, 5 Jan 2004 13:13:12 GMT
Content-Length: 112

<html>
<head>
<title>HTTP Response Example</title> </head>
<body>
Welcome to Brainy Software
</body>
</html>      

第一行,

HTTP/1.1 200 OK

表示協定、狀态和狀态描述。

之後表示響應頭部。

響應頭部和主體内容之間使用空行來分離。

Socket

Socket,又叫套接字,是網絡連接配接的一個端點(end point)。套接字允許應用程式從網絡中讀取和寫入資料。兩個不同計算機的不同程序之間可以通過連接配接來發送和接受資料。A應用要向B應用發送資料,A應用需要知道B應用所在的IP位址和B應用開放的套接字端口。java裡面使用

java.net.Socket

來表示一個套接字。

java.net.Socket

最常用的一個構造方法為:

public Socket(String host, int port);

,host表示主機名或ip位址,port表示套接字端口。我們來看一個例子:

Socket socket = new Socket("127.0.0.1", "8080");
OutputStream os = socket.getOutputStream(); 
boolean autoflush = true;
PrintWriter out = new PrintWriter( socket.getOutputStream(), autoflush);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputstream()));

// send an HTTP request to the web server 
out.println("GET /index.jsp HTTP/1.1"); 
out.println("Host: localhost:8080"); 
out.println("Connection: Close");
out.println();

// read the response
boolean loop = true;
StringBuffer sb = new StringBuffer(8096); 
while (loop) {
    if (in.ready()) { 
        int i=0;
        while (i != -1) {
            i = in.read();
            sb.append((char) i); 
        }
        loop = false;
    }
    Thread.currentThread().sleep(50L);
}      

這兒通過

socket.getOutputStream()

來發送資料,使用

socket.getInputstream()

來讀取資料。

ServerSocket

Socket表示一個用戶端套接字,任何時候如果你想發送或接受資料,都需要構造建立一個Socket。現在假如我們需要一個伺服器端的應用程式,我們需要額外考慮更多的東西。因為伺服器需要随時待命,它不清楚什麼時候一個用戶端會連接配接到它。在java裡面,我們可以通過

java.net.ServerSocket

來表示一個伺服器套接字。

ServerSocket和Socket不同,它需要等待來自用戶端的連接配接。一旦有用戶端和其建立了連接配接,ServerSocket需要建立一個Socket來和用戶端進行通信。

ServerSocket有很多的構造方法,我們拿其中的一個來舉例子。

public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException;
new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1"));      
  1. port表示端口
  2. backlog表示隊列的長度
  3. bindAddr表示位址

HttpServer

我們這兒還是看一個例子。

HttpServer表示一個伺服器端入口,提供了一個main方法,并一直在8080端口等待,直到用戶端建立一個連接配接。這時,伺服器通過生成一個Socket來對此連接配接進行處理。

public class HttpServer {

  /** WEB_ROOT is the directory where our HTML and other files reside.
   *  For this package, WEB_ROOT is the "webroot" directory under the working
   *  directory.
   *  The working directory is the location in the file system
   *  from where the java command was invoked.
   */
  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() {
    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);
    }

    // Loop waiting for a request
    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;
      }
    }
  }
}      

Request對象主要完成幾件事情

  • 解析請求資料
  • 解析uri(請求資料第一行)
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);
    }
    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(\' \');
    if (index1 != -1) {
      index2 = requestString.indexOf(\' \', index1 + 1);
      if (index2 > index1)
        return requestString.substring(index1 + 1, index2);
    }
    return null;
  }

  public String getUri() {
    return uri;
  }

}      

Response主要是向用戶端發送檔案内容(如果請求的uri指向的檔案存在)。

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) {
          output.write(bytes, 0, ch);
          ch = fis.read(bytes, 0, BUFFER_SIZE);
        }
      }
      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();
    }
  }
}      

總結

在看了上面的例子之後,我們驚奇地發現,在Java裡面實作一個web伺服器真容易,代碼也非常簡單和清晰!

既然我們能很簡單地實作web伺服器,為啥我們還需要tomcat呢?它又給我們帶來了哪些元件和特性呢,它又是怎麼組裝這些元件的呢,後續章節我們将逐層分析。

這是我們後面将要分析的内容,讓我們拭目以待!