给出一个java实现web服务器的例子
时间: 2024-02-16 19:00:19 浏览: 56
java 与web服务器链接的实例
好的,以下是一个简单的Java实现Web服务器的例子:
```
import java.io.*;
import java.net.*;
public class SimpleWebServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("Web服务器已启动,监听端口:8080");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("收到来自 " + clientSocket.getInetAddress().getHostAddress() + " 的HTTP请求");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String requestLine = in.readLine();
System.out.println("请求头:" + requestLine);
String[] requestParts = requestLine.split(" ");
String method = requestParts[0];
String path = requestParts[1];
if (!method.equals("GET")) {
clientSocket.close();
continue;
}
File file = new File("." + path);
if (!file.exists()) {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
out.println("HTTP/1.1 404 Not Found");
out.println();
out.close();
continue;
}
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fileInputStream.read(data);
OutputStream outputStream = clientSocket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
printWriter.println("HTTP/1.1 200 OK");
printWriter.println("Content-Type: text/html");
printWriter.println("Content-Length: " + file.length());
printWriter.println();
outputStream.write(data);
printWriter.close();
fileInputStream.close();
clientSocket.close();
System.out.println("已向 " + clientSocket.getInetAddress().getHostAddress() + " 发送HTTP响应");
}
}
}
```
运行这段代码后,你可以在浏览器中输入 `http://localhost:8080` 来访问该Web服务器。它会返回当前工作目录下的 `index.html` 文件的内容。如果该文件不存在,则会返回404 Not Found错误。你可以根据需要修改代码中的端口号和默认文件名。
阅读全文