用java实现一个简易web服务器
时间: 2023-11-11 15:05:52 浏览: 93
以下是一个简单的 Java Web 服务器的实现:
```
import java.io.*;
import java.net.*;
public class SimpleWebServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8080);
while (true) {
Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
OutputStream out = clientSocket.getOutputStream();
String request = in.readLine();
if (request.startsWith("GET /")) {
String[] parts = request.split(" ");
String filename = parts[1].substring(1);
File file = new File(filename);
if (file.exists()) {
out.write("HTTP/1.0 200 OK\r\n\r\n".getBytes());
FileInputStream fileIn = new FileInputStream(file);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileIn.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
} else {
out.write("HTTP/1.0 404 Not Found\r\n\r\n".getBytes());
out.write("<h1>404 Not Found</h1>".getBytes());
}
}
out.close();
in.close();
clientSocket.close();
}
}
}
```
这个服务器监听 8080 端口,当有客户端连接时,会读取客户端发来的请求,并根据请求的文件名返回相应的文件内容。如果文件不存在,则返回 404 Not Found 错误。这是一个非常简单的实现,仅供参考。
阅读全文