手写一个民用Tomcat (06)
手写一个简易的民用Tomcat需要实现基本的Web服务器功能,例如接收HTTP请求、解析请求、处理静态资源和Servlet处理。以下是一个非常简化的实现,仅提供基本功能以理解原理:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
public class SimpleTomcat {
private int port = 8080;
private String webAppDirectory = "webapp";
private Map<String, Servlet> servlets = new HashMap<>();
public SimpleTomcat(String webAppDirectory) {
this.webAppDirectory = webAppDirectory;
}
public void start() throws IOException {
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server started on port " + port);
while (true) {
Socket clientSocket = serverSocket.accept();
processRequest(clientSocket);
}
}
private void processRequest(Socket clientSocket) throws IOException {
InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
PrintWriter writer = new PrintWriter(outputStream, true);
// 简化:只处理GET方法,不处理POST和其他HTTP方法
String requestLine = reader.readLine();
String method = requestLine.split(" ")[0];
if (!method.equalsIgnoreCase("GET")) {
writer.println("HTTP/1.1 405 Method Not Allowed");
writer.println("Content-Type: text/plain");
writer.println();
writer.println("Method Not Allowed");
return;
}
String path = requestLine.split(" ")[1];
if (path.equals("/")) {
path += "index.html"; // 默认页面
}
File file = new File(webAppDirectory, path);
if (file.exists()) {
writer.println("HTTP/1.1 200 OK");
writer.println("Content-Type: text/html");
writer.println();
writeFileContent(writer, file);
} else {
Servlet servlet = servlets.get(path);
if (servlet != null) {
servlet.service(writer, reader);
} else {
writer.println("HTTP/1.1 404 Not Found");
writer.println("Content-Type: text/plain");
writer.println();
writer.println("Not Found");
}
}
writer.close();
reader.
评论已关闭