用java举一个web服务器实现功能的例子
时间: 2024-02-16 21:00:48 浏览: 139
以下是使用Java实现一个简单的Web服务器的示例代码:
```java
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
public class SimpleWebServer {
public static void main(String[] args) throws IOException {
int port = 8080;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server is listening on port " + port);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected from " + clientSocket.getInetAddress().getHostAddress());
InputStream inputStream = clientSocket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String request = reader.readLine();
System.out.println("Request: " + request);
String[] tokens = request.split(" ");
String method = tokens[0];
String path = tokens[1];
if (method.equals("GET")) {
Path filePath = Paths.get("." + path);
if (Files.exists(filePath) && !Files.isDirectory(filePath)) {
byte[] fileContent = Files.readAllBytes(filePath);
OutputStream outputStream = clientSocket.getOutputStream();
outputStream.write("HTTP/1.1 200 OK\r\n".getBytes());
outputStream.write(("Content-Type: " + Files.probeContentType(filePath) + "\r\n").getBytes());
outputStream.write(("Content-Length: " + fileContent.length + "\r\n").getBytes());
outputStream.write(("Date: " + new Date() + "\r\n").getBytes());
outputStream.write("\r\n".getBytes());
outputStream.write(fileContent);
outputStream.flush();
} else {
OutputStream outputStream = clientSocket.getOutputStream();
outputStream.write("HTTP/1.1 404 Not Found\r\n".getBytes());
outputStream.write(("Date: " + new Date() + "\r\n").getBytes());
outputStream.write("\r\n".getBytes());
outputStream.flush();
}
}
clientSocket.close();
System.out.println("Client disconnected");
}
}
}
```
这个简单的Web服务器监听8080端口,当接收到客户端的请求后,根据请求路径读取相应的文件并返回给客户端。如果文件不存在,则返回404错误。这个示例仅仅是一个初步的实现,还需要进行优化和改进,例如处理POST请求、支持多线程等。
阅读全文