1. 程式人生 > >JAVA實現簡易HTTP伺服器

JAVA實現簡易HTTP伺服器

說實話,之前完全沒有想過,我還能寫出伺服器。感覺伺服器這麼高階的東西,能會用就不錯了,還能寫。

不吐槽了,開始了。
這次的作業是搭建一個伺服器,要能接收請求,並給瀏覽器返回正確響應。
專案的下載地址

專案目標:實現一個簡易的多執行緒伺服器,可以處理來自瀏覽器的請求(GET/POST),並做出正確的迴應。
請求分以下四種類型:
1. 無引數,文字檔案型別
2. 無引數,圖片檔案型別
3. 有引數,GET方式請求,並完成表單驗證(登陸驗證)
4. 有引數,POST方式請求,並完成表單驗證(登陸驗證)

首先,應該明確這個專案的基本實現原理,從瀏覽器讀入使用者請求的資訊,伺服器解析並記錄返回的檔名和引數列表,如果檔案存在,用流讀取檔案,並返回到瀏覽器上,如果不存在,返回相應的提示資訊,引數列表和伺服器儲存的相同的話,返回登陸成功,否則返回失敗。

第一步,既然要解析從瀏覽器傳過來的資訊,那就要明白傳過來資訊的所使用的協議HTTP\UDP\FTP 和 URL的組成元素,因為是簡易伺服器,我們就只解析HTTP協議先。

這裡寫圖片描述

Request是指從客戶端到伺服器端的請求訊息
Request 訊息分為3部分,第一部分叫請求行, 第二部分叫http header, 第三部分是body. header和body之間有個空行,結構如下圖

這裡寫圖片描述

Method表示請求方法,比如”POST”,”GET”,
Path-to-resoure表示請求的資源,
Http/version-number 表示HTTP協議的版本號,
當使用的是”GET” 方法的時候, body是為空的,當使用”POST”,body不為空,但是沒有換行,readline()方法不能讀

Response是指伺服器端到客戶端的響應資訊
和Request訊息的結構基本一樣。 同樣也分為三部分,第一部分叫request line, 第二部分叫request header,第三部分是body. header和body之間也有個空行, 結構如下圖

這裡寫圖片描述

狀態碼用來告訴HTTP客戶端,HTTP伺服器是否產生了預期的Response. HTTP/1.1中定義了5類狀態碼,1XX 提示資訊 - 表示請求已被成功接收,繼續處理;2XX 成功 - 表示請求已被成功接收,理解,接受;3XX 重定向 - 要完成請求必須進行更進一步的處理;4XX 客戶端錯誤 - 請求有語法錯誤或請求無法實現;5XX 伺服器端錯誤 - 伺服器未能實現合法的請求,當然不寫也是可以得,狀態碼就是便於程式設計師去分析當前頁面是正確響應還是錯誤的。

第二步,在瞭解URL和HTTP協議之後,就可以開始構建專案了。

目前這個專案的UML圖

這裡寫圖片描述

第三步,準備文字、圖片、HTML檔案,然後開始編編編

效果圖:(埠號:23333)2333…
預設訪問
這裡寫圖片描述

aaron.txt
這裡寫圖片描述

a.jpg
這裡寫圖片描述

GET/POST請求
注意位址列的變化
login.html(GET)
這裡寫圖片描述

login.html(GET) (登陸失敗情況)
這裡寫圖片描述

login.html(GET) (登陸成功情況)
這裡寫圖片描述

login.html(POST)
這裡寫圖片描述

login.html(POST) (登陸失敗情況)
這裡寫圖片描述

login.html(POST) (登陸成功情況)
這裡寫圖片描述

部分原始碼:(全部原始碼去上面下載)

//Server.java
package cn.net.sight.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
import cn.net.sight.thread.ServerThread;

public class Server {
    private static ServerSocket server;
    private static Properties properties;
    private int port;

    static {
        properties = new Properties();
        try {
            properties.load(new FileInputStream(new File("src/resources/property.proterties")));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //initialize the server
    public void init() {
        try {
            port = Integer.parseInt(properties.getProperty("port"));
            server = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //receive the request from the web browser
    public void receive() {
        Socket clientSocket = new Socket();
        try {
            clientSocket = server.accept();
        } catch (IOException e) {
            e.printStackTrace();
        }

        ServerThread thread = new ServerThread(clientSocket);
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    //startup server
    public static void main(String[] args) {
        Server Aaroncat = new Server();
        Aaroncat.init();
        System.out.println("----Aaroncat has startup----");
        while(true){
            Aaroncat.receive();
        }
    }
}
//Request.java
package cn.net.sight.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import cn.net.sight.util.MessageUtil;

public class Request {

    private InputStream input; // Socket --> InputStream
    private Socket socket; // client --> socket
    private BufferedReader buffer; // InputStream --> BufferedReader
    private String schema; // the schema of the request GET or POST
    private String requestFileName; // exact file name
    private String requestData; // file name + <key=value>...
    private String values_Str; // a string the user input in the form
    private int paramLength; // using in the POST: the length of parameters
    private Map<String, String> socketValues;// values_str --> MAP
    private PrintStream print;

    protected MessageUtil messageUtil = new MessageUtil();

    //省略了全部的setter() getter()

    private void doSchema(String firstLineInData) throws IOException {
        socketValues = new HashMap<String, String>();
        if (this.schema.equals("GET")) {
            // GET請求 --> 包含檔名和引數鍵值對
            // 實現了對FileName、SocketValues的賦值
            this.setRequestData(messageUtil.getRequestData(firstLineInData));
            if (this.requestData.contains("?")) {
                this.setRequestFileName(messageUtil.getFileName(this.getRequestData()));
                this.setSocketValues(messageUtil.getValues(this.getRequestData()));
            } else {
                // GET請求 -->只包含檔名
                // 實現了對FileName的賦值
                this.setRequestFileName(requestData);
            }
        } else {
            // POST請求 第一行只包含檔名
            // 實現了對FileName、SocketValues的賦值
            this.setRequestFileName(messageUtil.getRequestData(firstLineInData));
            this.getUserInfo(buffer);
        }
    }

    private void getUserInfo(BufferedReader br) throws IOException {
        while (this.buffer.ready()) {
            String remained = buffer.readLine();
            if (remained.contains("Content-Length")) {
                String[] temp = remained.split(" ");
                this.setParamLength(Integer.parseInt(temp[1]));
                break;
            }
        }
        buffer.readLine();
        String userInfo = "";
        for (int i = 0; i < this.getParamLength(); i++) {
            userInfo += (char) buffer.read();
        }
        this.setValues_Str(userInfo);
        this.setSocketValues(messageUtil.getValues(this.getValues_Str()));
    }

    public Request(Socket clientSocket) throws IOException {
        this.setSocket(clientSocket);
        this.setPrint(new PrintStream(clientSocket.getOutputStream()));
        this.setInput(clientSocket.getInputStream());
        this.setBuffer(new BufferedReader(new InputStreamReader(clientSocket.getInputStream())));

        // get something from the first line
        String firstLineInData = buffer.readLine();

        this.setSchema(messageUtil.getSchema(firstLineInData)); // 獲得請求方式Schema

        doSchema(firstLineInData); // 對Schema進行判斷

    }
}
//Response.java
package cn.net.sight.server;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Date;
import java.util.Map;
import cn.net.sight.util.FileUtil;
import cn.net.sight.util.LoginUtil;

public class Response {

    private String fileName;
    private Map<String, String> userValues;
    private PrintStream ps;
    private Request request;
    private Socket clientSocket;

    protected FileUtil fileUtil = new FileUtil();
    protected LoginUtil loginUtil = new LoginUtil();

    public String getFileName() {
        return fileName;
    }

    //省略了全部的setter() 和 getter()

    public Response(Request request) {
        this.setRequest(request);
        this.setClientSocket(request.getSocket());
        this.setFileName(request.getRequestFileName());
        userValues = this.request.getSocketValues();

        try {
            this.init();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void showup(String fileName) throws IOException {
        this.ps = this.request.getPrint();
        // 要處理正常檔名和空檔名
        if (!fileName.equals("")  && !fileName.equals("error.html")) {
            this.ps.println("HTTP/1.1 200 OK");
            this.ps.println();
            fileUtil.readFile(fileName, ps);
        } else if (fileName.equals("error.html")) {
            ps.println("HTTP/1.1 404 fileNotFound");
            ps.println();
            fileUtil.readFile("error.html", ps);
        } else {
            ps.println(new Date().toString());
        }
        if (ps != null){
            ps.close();
        }
    }

    public void init() throws IOException {
        //如果資訊MAP是空,則代表是普通檔案或者是預設訪問
        if (userValues.isEmpty()) {
            if (fileName != "") {
                this.showup(fileName);
            } else {
                this.ps = this.request.getPrint();
                ps.println(new Date().toString());
                if(ps != null) ps.close();
                if(clientSocket != null)clientSocket.close();
            }
        } else {
            //如果資訊MAP不為空,代表是GET/POST請求,並帶有引數鍵值對
            this.Check(userValues, fileName);
        }

    }

    public void Check(Map<String, String> values_list, String respFileName) throws IOException {
        // 驗證使用者輸入資訊的合法性
        if (loginUtil.isValid(values_list)) {
            this.showup(respFileName);
        } else {
            this.showup("error.html");
        }
    }

}

//ServerThread.java
package cn.net.sight.thread;

import java.io.IOException;
import java.net.Socket;
import cn.net.sight.server.Response;
import cn.net.sight.server.Request;

public class ServerThread extends Thread {
    private Socket clientSocket;
    private Request request;
    private Response response;

    public ServerThread() {
        super();
    }

    public ServerThread(Socket clientSocket) {
        super();
        this.clientSocket = clientSocket;
    }

    public Socket getClientSocket() {
        return clientSocket;
    }

    public void setClientSocket(Socket clientSocket) {
        this.clientSocket = clientSocket;
    }

    public Request getRequest() {
        return request;
    }

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

    public Response getResponse() {
        return response;
    }

    public void setResponse(Response response) {
        this.response = response;
    }

    public void run(){
        super.run();
        try {
            this.setRequest(new Request(clientSocket));
            this.response = new Response(request);
            this.setResponse(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
//FileUtil.java
package cn.net.sight.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;

public class FileUtil {
    private static final int BUFFER_SIZE = 1024;

    public void readFile(String file_Name, PrintStream ps) throws IOException {
        byte[] buffer = new byte[BUFFER_SIZE];
        int length;
        File file = new File("src/resources/" + file_Name);
        FileInputStream fis = null;

        if (file.exists()) {
            try {
                fis = new FileInputStream(file);
                while ((length = fis.read(buffer)) != -1) {
                    ps.write(buffer, 0, length);
                    ps.flush();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            ps.println("File not found");
            ps.println();
        }
    }
}
//LoginUtil.java
package cn.net.sight.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

public class LoginUtil {
    protected boolean flag = false;
    protected Map<String, String> values;
    private static Properties properties;

    static {
        properties = new Properties();
        try {
            properties.load(new FileInputStream(new File("src/resources/property.proterties")));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public Map<String, String> getValues() {
        return values;
    }

    public void setValues(Map<String, String> values) {
        this.values = values;
    }

    // 驗證使用者資訊的合法性(應用JDBC橋,連線資料庫)
    public boolean isValid(Map<String, String> values) {

        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        if (values.get("username").equals(username)) {
            if (values.get("password").equals(password)) {
                flag = true;
                System.out.println("The user " + values.get("username") + " was log the server.");
                return flag;
            }
        } else {
            System.out.println("Forbide the " + values.get("username") + " log the server");
            return flag;
        }
        return false;
    }
}
//MessageUtil.java
package cn.net.sight.util;

import java.util.HashMap;
import java.util.Map;

public class MessageUtil {

    // schema : GET or POST
    public String getSchema(String requestMsg) {
        String[] result = new String[1];
        if (requestMsg.contains(" ")) {
            result = requestMsg.split(" ");
            requestMsg = result[0];
        }
        return requestMsg;
    }

    // get the resquestData = (filename + map<S,S>)
    public String getRequestData(String firstLineInData) {
        String[] result = new String[10];
        result = firstLineInData.split(" ");
        firstLineInData = result[1].substring(1);
        return firstLineInData;
    }

    // get the filename from the requestData
    public String getFileName(String requestData) {
        String[] result = new String[10];
        result = requestData.split("[?]");
        return result[0];
    }

    // save the info into the map<S,S>
    public Map<String, String> getValues(String requestData) {
        Map<String, String> values = new HashMap<String, String>();
        String[] result = new String[10];
        String regex = "[&=]";

        if (requestData.contains("?")) {
            result = requestData.split("[?]");
            String data_List = result[1];
            result = data_List.split(regex);
            for (int i = 0; i < result.length - 1; i += 2) {
                values.put(result[i], result[i + 1]);
            }
            return values;
        } else {
            result = requestData.split(regex);
            for (int i = 0; i < result.length - 1; i += 2) {
                values.put(result[i], result[i + 1]);
            }
            return values;
        }
    }

}

整個專案結構
這裡寫圖片描述