【吃透Java手写】4-Tomcat-简易版
以下是一个简化版的Tomcat服务器的核心代码示例,它展示了如何接收HTTP请求并返回响应:
import java.io.*;
import java.net.*;
public class SimpleTomcatServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
while (true) {
Socket socket = serverSocket.accept();
handleRequest(socket);
}
}
private static void handleRequest(Socket socket) throws IOException {
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
// 读取HTTP请求
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
System.out.println("Received: " + line);
// 写入HTTP响应
PrintWriter writer = new PrintWriter(outputStream, true);
writer.println("HTTP/1.1 200 OK");
writer.println("Content-Type: text/html");
writer.println();
writer.println("<html><body><h1>Hello, World!</h1></body></html>");
socket.close();
}
}
这段代码创建了一个简易的Web服务器,监听8080端口。每当接收到一个HTTP请求,它就会返回一个简单的HTML页面。这个示例主要用于教学目的,实际的Tomcat服务器要复杂得多,包含更多功能,如解析HTTP头部、处理静态资源、JSP支持、安全性等。
评论已关闭