import java.io.*;
import java.net.*;
public class HTTPServer {
public static final int PORT = 8080;
public static final String WEB_ROOT = "www/";
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("HTTP Server is running on port " + PORT);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Accepted connection from " + clientSocket.getInetAddress().getHostName());
InputStream inputStream = clientSocket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String request = reader.readLine();
System.out.println("Received request: " + request);
String[] tokens = request.split(" ");
String filePath = WEB_ROOT + tokens[1];
FileInputStream fileInputStream = null;
boolean fileExists = true;
try {
fileInputStream = new FileInputStream(filePath);
} catch (FileNotFoundException e) {
fileExists = false;
}
String responseStatus = null;
String responseBody = null;
if (fileExists) {
responseStatus = "HTTP/1.1 200 OK";
responseBody = readFile(fileInputStream);
} else {
responseStatus = "HTTP/1.1 404 Not Found";
responseBody = "<h1>404 Not Found</h1>";
}
String response = responseStatus + "\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: " + responseBody.length() + "\r\n" +
"\r\n" + responseBody;
OutputStream outputStream = clientSocket.getOutputStream();
outputStream.write(response.getBytes());
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readFile(FileInputStream fileInputStream) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
return outputStream.toString();
}
}
在上面的代码中,我们定义了一个名为 HTTPServer 的类,它使用 Java 的 Socket API 实现了一个简单的 HTTP 服务器。服务器监听 8080 端口,并在接收到客户端请求时提供静态网页文件。
在 main 方法中,我们首先创建一个 ServerSocket 对象,该对象绑定到端口 8080 并开始监听连接。然后,我们进入一个无限循环,在每次迭代中接受一个客户端连接,并读取其请求。我们从请求中提取文件路径,并尝试打开该文件以读取其内容。如果文件存在,则返回 HTTP 200 状态码和文件内容作为响应;否则,返回 HTTP 404 状态码和简单的“404 Not Found”消息。
最后,我们将响应发送回客户端,并关闭连接。在发送响应之前,我们需要将响应内容转换为字节数组,并计算内容长度和响应头部分。
要运行此代码,请将其保存在名为 HTTPServer.java 的文件中,并将 www/ 目录中的静态