使用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; // Set your port here
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("HTTP Server is listening on port " + PORT);
while (true) { // Loop to accept and handle incoming requests
Socket clientSocket = serverSocket.accept(); // Accept the connection
System.out.println("Client connected: " + clientSocket.getRemoteSocketAddress()));
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))); // Get input stream from client socket
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)); // Get output stream from client socket and set buffer size to 1KB (for faster response)
String requestLine = in.readLine(); // Read first line of the request
if (requestLine == null || requestLine.trim().isEmpty()) {
System.out.println("Invalid request line");
out.close();
in.close();
clientSocket.close();
continue;
}
String method = requestLine.substring(0, requestLine.indexOf(' '))).trim(); // Extract method from request line
String url = requestLine.substring(requestLine.indexOf(' ') + 1)).trim(); // Extract URL from request line
System.out.println("Received method: " + method);
System.out.println("Received URL: " + url);
if (method.equalsIgnoreCase("GET")) { // Handle GET requests
out.print("HTTP/1.1 200 OK\r\n");
out.print("<html><head><title>Example GET Response</title></head><body><h1>Here is the content for your GET request:</h1>" + "<p>" + "This is a sample text generated specifically for this HTTP server instance.</p>" + "</body></html>\r\n"); // Generate HTML response
out.flush();
} else if (method.equalsIgnoreCase("POST")) { // Handle POST requests (for simplicity, just print the received data)
out.print("<h1>Received POST Data:</h1>\n");
out.print("<pre>" + url + "</pre>\n");
out.print("<p>This is the raw content of your POST request:</p>\n");
out.flush();
} else { // Handle other methods (not implemented in this example)
out.print("HTTP/1.1 405 Method Not Allowed\r\n");
out.flush();
}
}
} catch (IOException e) {
System.out.println("Error occurred while processing the request: " + e.getMessage());
e.printStackTrace();
} finally {
try {
in.close();
out.close();
clientSocket.close();
} catch (IOException e) {
System.out.println("Error occurred while closing resources: " + e.getMessage());
e.printStackTrace();
}
}
}
}
这个Java程序创建了一个HTTP服务器,它在指定的端口(8000)上监听。当有客户端连接时,会读取客户端发送的请求,并根据请求类型(GET/POST等)处理响应。
还没有评论,来说两句吧...