如何用Java实现一个简单的HTTP服务器?
在Java中,我们可以使用内置的ServerSocket
和Socket
类来创建一个简单的HTTP服务器。以下是一个基本的例子:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleHttpServer {
private static final int PORT = 8000; // Change this to the desired port
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("HTTP server started on port " + PORT);
while (true) {
Socket clientSocket = serverSocket.accept(); // Wait for a connection
handleClientConnection(clientSocket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void handleClientConnection(Socket clientSocket) {
try (OutputStream outputStream = new FileOutputStream("/temp/index.html")); // Assuming the server is serving an index.html file
OutputStream clientOutputStream = clientSocket.getOutputStream();) {
// Write the HTTP response headers
String httpResponseHeaders = "HTTP/1.1 200 OK\r\n";
byte[] headersBytes = httpResponseHeaders.getBytes();
// Write the HTTP response body (index.html file)
byte[] indexHtmlContentBytes = new byte[] {
'<!DOCTYPE html>', // HTML5 declaration
'<html lang="en">', // HTML tag with lang attribute
'<head>', // Head tag
'<meta charset="UTF-8">', // Character encoding meta tag
'<title>Simple HTTP Server</title>', // Title meta tag
'</head>', // End of head tag
'<body>', // Body tag
'<h1>Welcome to the Simple HTTP Server!</h1>', // Heading 1 tag
'</body>', // End of body tag
'</html>' // End of HTML document
};
// Write the full response (headers + body)
byte[] fullResponseBytes = headersBytes.concat(indexHtmlContentBytes));
// Send the full response to the client
clientOutputStream.write(fullResponseBytes);
clientOutputStream.flush();
} catch (IOException e) {
System.err.println("Error handling client connection: " + e.getMessage());
e.printStackTrace();
}
}
}
这个简单的HTTP服务器会在8000
端口监听连接,并为每个请求返回一个200状态的成功响应。请注意,这个例子假设服务器会提供一个名为index.html
的文件作为响应内容。如果实际情况不同,请相应调整代码。
还没有评论,来说两句吧...