使用Java实现简单HTTP服务器实例

原创 矫情吗;* 2024-12-02 04:54 29阅读 0赞

在Java中,我们可以使用内置的ServerSocketSocket类来创建一个简单的HTTP服务器。以下是一个基本的例子:

  1. import java.io.*;
  2. import java.net.ServerSocket;
  3. import java.net.Socket;
  4. public class SimpleHTTPServer {
  5. private static final int PORT = 8000; // Set your port here
  6. public static void main(String[] args) {
  7. try (ServerSocket serverSocket = new ServerSocket(PORT)) {
  8. System.out.println("HTTP Server is listening on port " + PORT);
  9. while (true) { // Loop to accept and handle incoming requests
  10. Socket clientSocket = serverSocket.accept(); // Accept the connection
  11. System.out.println("Client connected: " + clientSocket.getRemoteSocketAddress()));
  12. BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))); // Get input stream from client socket
  13. PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)); // Get output stream from client socket and set buffer size to 1KB (for faster response)
  14. String requestLine = in.readLine(); // Read first line of the request
  15. if (requestLine == null || requestLine.trim().isEmpty()) {
  16. System.out.println("Invalid request line");
  17. out.close();
  18. in.close();
  19. clientSocket.close();
  20. continue;
  21. }
  22. String method = requestLine.substring(0, requestLine.indexOf(' '))).trim(); // Extract method from request line
  23. String url = requestLine.substring(requestLine.indexOf(' ') + 1)).trim(); // Extract URL from request line
  24. System.out.println("Received method: " + method);
  25. System.out.println("Received URL: " + url);
  26. if (method.equalsIgnoreCase("GET")) { // Handle GET requests
  27. out.print("HTTP/1.1 200 OK\r\n");
  28. 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
  29. out.flush();
  30. } else if (method.equalsIgnoreCase("POST")) { // Handle POST requests (for simplicity, just print the received data)
  31. out.print("<h1>Received POST Data:</h1>\n");
  32. out.print("<pre>" + url + "</pre>\n");
  33. out.print("<p>This is the raw content of your POST request:</p>\n");
  34. out.flush();
  35. } else { // Handle other methods (not implemented in this example)
  36. out.print("HTTP/1.1 405 Method Not Allowed\r\n");
  37. out.flush();
  38. }
  39. }
  40. } catch (IOException e) {
  41. System.out.println("Error occurred while processing the request: " + e.getMessage());
  42. e.printStackTrace();
  43. } finally {
  44. try {
  45. in.close();
  46. out.close();
  47. clientSocket.close();
  48. } catch (IOException e) {
  49. System.out.println("Error occurred while closing resources: " + e.getMessage());
  50. e.printStackTrace();
  51. }
  52. }
  53. }
  54. }

这个Java程序创建了一个HTTP服务器,它在指定的端口(8000)上监听。当有客户端连接时,会读取客户端发送的请求,并根据请求类型(GET/POST等)处理响应。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,29人围观)

还没有评论,来说两句吧...

相关阅读