国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

基于Java的Web服務器工作原理(三)

2019-11-18 16:22:55
字體:
來源:轉載
供稿:網友

  Request 類

  Request 類對應 HTTP 請求。創(chuàng)建這個類的實例,并傳給它從 Socket 獲得的 InputStream 對象,從而捕獲與客戶端的通信。呼叫 InputStream 對象的 read 方法中的一個就可以得到 HTTP 請求的原始數據。
  Request 類有二個 public 方法 parse 與 getUri。parse 方法解析 HTTP 請求的原始數據。它做的事情不多--唯一它使之有效的信息是 HTTP 請求的 URI ,這個通過呼叫私有方法 parseUri 來獲得。parseUri 方法把 URI 作為一個變量。調用 getUri 方法可以得到 HTTP 請求的 URI 。
  要明白 parse 與 parseUri 的工作原理,你需要知道 HTTP 請求的結構,由 RFC2616 定義。
  一個 HTTP 請求包括三個部分:
Request line
Headers
Message body
  現在,我們只需要關注 HTTP 請求的第一部分--請求行。請求行以方法記號開始,接著是請求的 URI 與協議版本,以回車換行符結束。請求行的元素之間以空格分開。例如,一個用 GET 方法的 index.Html 文件的請求行如下:
GET /index.html HTTP/1.1
  parse 方法從 socket 的 InputStream 傳遞給 Request 對象中讀取字節(jié)流,把這個字節(jié)數組存在緩沖里。然后,它把 buffer 字節(jié)數組里的字節(jié)放入叫做 request 的 StringBuffer 對象中,再把 StringBuffer 替換成 String 傳遞給 parseUri 方法。
  parse 方法的代碼如列表 1.2
Listing 1.2. The Request class' parse method

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());
}

  parseUri 方法查找請求行的第一個與第二個空格,從而從請求行獲得了 URI 。列表 1.3 展示了 parseUri 方法的代碼。
Listing 1.3. The Request class' parseUri method

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;
}

  response 類

  Response 類描述 HTTP 響應。它的構建方法接受 OutputStream 對象,如下:
public Response(OutputStream output) {
    this.output = output;
}
  Response 對象通過傳遞從 socket 獲得的 OutputStream 對象到 HttpServer 類的 await 方法而創(chuàng)建。
  Response 類有二個公共方法 setRequest 與 setStaticResource 。
setRequest 用來傳遞 Request 對象到 Response 對象。它比較簡單,代碼如列表 1.4 所示:
Listing 1.4. The Response class' setRequest method

public void setRequest(Request request) {
    this.request = request;
}

  sendStaticResource 方法用來發(fā)送靜態(tài)的資源,例如 HTML 文件。它的實現如列表 1.5 所示:
Listing 1.5. The Response class' sendStaticResource method

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();
    }
}

  SendStaticResource 方法非常簡單。
它首先通過傳遞父與子目錄到 File 類的構建方法從而實例化 java.io.File 類。
File file = new File(HttpServer.WEB_ROOT, request.getUri());
  然后檢查這個文件是否存在。如果存在,則 sendStaticResource 方法傳遞 File 對象創(chuàng)建 java.io.FileInputStream 對象。然后調用 FileInputStream 的 read 方法,并把字節(jié)數組寫到 OutputStream 對象 output 。就這樣,靜態(tài)資源的內容作為原始數據被發(fā)送到瀏覽器。
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);
    }
}
  如果文件不存在,sendStaticResource 發(fā)送一個錯誤信息到瀏覽器。
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());

  編譯與運行應用程序

  要編輯與運行本文的應用,首先你需要解壓源碼 zip 文件。直接解壓出來的目錄被稱為工作目錄,它有三個子目錄:src/,classes/,lib/。要編譯應用,從工作目錄輸入如下命令:
javac -d . src/ex01/pyrmont/*.java
  -d 選項把結果寫到當前目錄,而不是 src/ 目錄。
  要運行應用,在當前工作目錄輸入如下命令:
java ex01.pyrmont.HttpServer
  測試這個應用,打開你的瀏覽器,在地址欄輸入如下地址:
http://localhost:8080/index.html
  你將在你的瀏覽器看到 index.html 顯示出來。

在控制臺,你看到如下的內容:
GET /index.html HTTP/1.1
Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)
Host: localhost:8080
Connection: Keep-Alive

GET /images/logo.gif HTTP/1.1
Accept: */*
Referer: http://localhost:8080/index.html
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)
Host: localhost:8080
Connection: Keep-Alive

  總結

  在這篇文章中(分為三個部分),你看到了一個簡單的 web 服務器的工作原理。本文相關的應用只包括了三個類,功能是不全面的。然而,它仍不失為一個好的學習工具。

matrix開源技術經Onjava授權翻譯并發(fā)布.
如果你對此文章有任何看法或建議,請到Matrix論壇發(fā)表您的意見.
注明: 如果對matrix的翻譯文章系列感興趣,請點擊oreilly和javaworld文章翻譯計劃查看詳細情況
您也可以點擊-fajaven查看翻譯作者的詳細信息.

(出處:http://m.survivalescaperooms.com)



發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 延长县| 滨州市| 金坛市| 顺平县| 平乡县| 康保县| 泸水县| 银川市| 恩施市| 探索| 龙游县| 包头市| 上饶市| 达尔| 青川县| 怀集县| 万荣县| 西安市| 黄梅县| 班戈县| 香格里拉县| 上林县| 自治县| 吉首市| 安庆市| 济南市| 吉木萨尔县| 桐城市| 洪江市| 黔东| 丹东市| 玉树县| 宝丰县| 洪江市| 正宁县| 任丘市| 海兴县| 什邡市| 邹平县| 岳普湖县| 靖边县|