簡單HTTP伺服器的Java實現

來源:互聯網
上載者:User

標籤:http伺服器   靜態頁面   http協議   

在web的最初階段是不支援web伺服器與使用者的互動的.也就是說web伺服器不能動態產生使用者要訪問的頁面,web伺服器提供給使用者的頁面都是提前產生好的.所以也說這種頁面是靜態頁面.
比如說使用者請求訪問http://localhost:8088/hello1.htm, 那麼web伺服器從自己的想要目錄下擷取hello1.htm(已經存在).然後通過HTTP協議返回給使用者.

下面我們來類比一下這個過程.因為HTTP協議是應用程式層協議,基於TCP,所以我們用Java的socket來編寫HTTP伺服器.

編寫HttpServer
import java.io.*;import java.net.*;public class HttpServer {    private static final int port = 8088;    private ServerSocket serverSocket = null;    public HttpServer() throws IOException {        serverSocket = new ServerSocket(port);        System.out.println("HTTPServer startup OK...");    }    public String getRequest(Socket socket) throws IOException {        InputStream socketIn = socket.getInputStream();        int size = socketIn.available();        byte[] requestBuff = new byte[size];        socketIn.read(requestBuff);        return new String(requestBuff);    }    public String getURI(String request) {        String firstLine = request.substring(0, request.indexOf("\r\n"));        String[] parts = firstLine.split(" ");        return parts[1];    }    public String getContentType(String URI) {        /* 決定HTTP響應本文的類型 */        String contentType;        if (URI.indexOf("html") != -1 || URI.indexOf("htm") != -1)            contentType = "text/html";        else if (URI.indexOf("jpg") != -1 || URI.indexOf("jpeg") != -1)            contentType = "image/jpeg";        else if (URI.indexOf("gif") != -1)            contentType = "image/gif";        else            contentType = "application/octet-stream";        return contentType;    }    public InputStream getResponseContent(String URI)            throws FileNotFoundException {        InputStream htmlInputStream = new FileInputStream(                System.getProperty("user.dir") + "/WebRoot" + URI);        return htmlInputStream;    }    public String assembleResponseHead(String URI, String contentType) {        /* 建立HTTP響應結果 */        // HTTP響應的第一行        String responseFirstLine = "HTTP/1.1 200 OK\r\n";        // HTTP回應標頭        String responseHeader = "Content-Type:" + contentType + "\r\n\r\n";        return responseFirstLine + responseHeader;    }    public void service() throws InterruptedException {        while (true) {            Socket socket;            try {                socket = serverSocket.accept();                String request = getRequest(socket);                System.out.println("HttpServer receive request:\n" + request);                String URI = getURI(request);                String contentType = getContentType(URI);                OutputStream out = socket.getOutputStream();                out.write(assembleResponseHead(URI, contentType).getBytes());                int len = 0;                byte[] buffer = new byte[128];                InputStream htmlInputStream = getResponseContent(URI);                while ((len = htmlInputStream.read(buffer)) != -1)                    out.write(buffer, 0, len);                Thread.sleep(1000);                socket.close(); // 關閉TCP串連            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }    }    public static void main(String[] args) throws IOException,            InterruptedException {        HttpServer httpServer = new HttpServer();        // System.out.println(System.getProperty("user.dir"));        httpServer.service();    }}
建立hello1.htm

然後在項目的目錄/WebRoot下放置一個hello1.htm頁面:

hello1.htm很簡單,顯示標題HelloWorld

<html><head><title>HelloWorld</title></head><body >  <h1>Hello</h1></body></html>
訪問hello1.htm

啟動HTTPServer,在瀏覽器訪問http://localhost:8088/hello1.htm,看到eclipse的Console輸出

GET /hello1.htm HTTP/1.1Host: localhost:8088Connection: keep-aliveCache-Control: max-age=0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.125 Safari/537.36Accept-Encoding: gzip, deflate, sdchAccept-Language: zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4

這是瀏覽器請求的HTTP訊息,包括了HTTP頭,請求方式,有時也有請求本文(這裡沒有).
瀏覽器顯示為:


這樣簡單的HTTPSever就算完成了,後續我將繼續研究類比一下Servlet的HTTP伺服器.

簡單HTTP伺服器的Java實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.