在框架橫行的年代,偶爾回到最原始的 Socket 與 HTTP 協定,反而能把「Web 伺服器到底在做什麼」看得一清二楚。下面這支迷你伺服器只做三件事:監聽埠號、解析請求行、把對應檔案回傳給客戶端;找不到檔案就回 404。
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class WebServer {
public static void main(String[] args) {
int port = 80;
if (args.length == 1) {
port = Integer.parseInt(args[0]);
}
new WebServer().serverStart(port);
}
// 預設監聽 80 埠
public void serverStart(int port) {
try {
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
Socket socket = serverSocket.accept();
new Processor(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
accept() 是阻塞的,每來一個連線就交給一個新的 Processor 執行緒去處理,主迴圈立刻回到等待狀態。這種「一連線一執行緒」的模型寫法簡單,但在高併發下會被執行緒數量限制,真實的伺服器會改用事件驅動或多執行緒池。
import java.io.*;
import java.net.Socket;
public class Processor extends Thread {
private Socket socket;
private final static String WEB_ROOT = "E:\\zhxh\\web\\SpringSecurity";
private InputStream inputStream;
private OutputStream out;
public Processor(Socket socket) {
this.socket = socket;
try {
inputStream = socket.getInputStream();
out = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
String fileName = parse(inputStream); // 取出請求行中的檔案名稱
sendFile(fileName);
}
public String parse(InputStream in) {
String fileName = "";
BufferedReader br = new BufferedReader(new InputStreamReader(in));
try {
String httpMessage = br.readLine(); // 第一行:方法、路徑、版本以空白分隔
String[] content = httpMessage.split(" ");
if (content.length != 3) {
sendErrorMessage(400, "客戶請求錯誤");
return null;
}
fileName = content[1];
} catch (IOException e) {
e.printStackTrace();
}
return fileName;
}
public void sendErrorMessage(int errorCode, String errorMessage) {
PrintStream pOut = new PrintStream(out);
pOut.println("HTTP/1.0 " + errorCode + " " + errorMessage);
pOut.println("content-type:text/html");
pOut.println();
pOut.println("<html><title>錯誤資訊</title><body><h1>errorCode:"
+ errorCode + "," + errorMessage + "</h1></body></html>");
pOut.close();
try {
out.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendFile(String fileName) {
PrintStream pOut = new PrintStream(out);
File file = new File(WEB_ROOT + fileName);
if (!file.exists()) {
sendErrorMessage(404, "資源不存在");
} else {
try {
InputStream in = new FileInputStream(file);
byte[] content = new byte[(int) file.length()];
in.read(content);
pOut.println("HTTP/1.0 200 查詢檔案");
pOut.println("content-length:" + content.length);
pOut.println();
pOut.write(content);
pOut.flush();
pOut.close();
out.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
HTTP 回應的最小組成就是「狀態行 + 標頭 + 空行 + 本文」,而空行是標頭結束的判準,少寫它就會讓瀏覽器一直等下去。另外可以看到,請求行只取了路徑部分,查詢字串、標頭、Cookie 全都被忽略——真實伺服器要處理的細節遠比這多。但把這一百來行跑起來,再用瀏覽器打開 https://localhost:8080/index.html 看到頁面時,你對「伺服器」這三個字的理解會完全不同。
提醒一句:這個範例沒有任何路徑安全防護,../ 就能跳出 WEB_ROOT,只能當作學習用途,切勿直接部署到任何可公開存取的環境。