如何用Java实现一个简单的HTTP服务器?

原创 系统管理员 2024-09-23 10:27 312阅读 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; // Change this to the desired port
  6. public static void main(String[] args) {
  7. try (ServerSocket serverSocket = new ServerSocket(PORT)) {
  8. System.out.println("HTTP server started on port " + PORT);
  9. while (true) {
  10. Socket clientSocket = serverSocket.accept(); // Wait for a connection
  11. handleClientConnection(clientSocket);
  12. }
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. }
  16. }
  17. private static void handleClientConnection(Socket clientSocket) {
  18. try (OutputStream outputStream = new FileOutputStream("/temp/index.html")); // Assuming the server is serving an index.html file
  19. OutputStream clientOutputStream = clientSocket.getOutputStream();) {
  20. // Write the HTTP response headers
  21. String httpResponseHeaders = "HTTP/1.1 200 OK\r\n";
  22. byte[] headersBytes = httpResponseHeaders.getBytes();
  23. // Write the HTTP response body (index.html file)
  24. byte[] indexHtmlContentBytes = new byte[] {
  25. '<!DOCTYPE html>', // HTML5 declaration
  26. '<html lang="en">', // HTML tag with lang attribute
  27. '<head>', // Head tag
  28. '<meta charset="UTF-8">', // Character encoding meta tag
  29. '<title>Simple HTTP Server</title>', // Title meta tag
  30. '</head>', // End of head tag
  31. '<body>', // Body tag
  32. '<h1>Welcome to the Simple HTTP Server!</h1>', // Heading 1 tag
  33. '</body>', // End of body tag
  34. '</html>' // End of HTML document
  35. };
  36. // Write the full response (headers + body)
  37. byte[] fullResponseBytes = headersBytes.concat(indexHtmlContentBytes));
  38. // Send the full response to the client
  39. clientOutputStream.write(fullResponseBytes);
  40. clientOutputStream.flush();
  41. } catch (IOException e) {
  42. System.err.println("Error handling client connection: " + e.getMessage());
  43. e.printStackTrace();
  44. }
  45. }
  46. }

这个简单的HTTP服务器会在8000端口监听连接,并为每个请求返回一个200状态的成功响应。请注意,这个例子假设服务器会提供一个名为index.html的文件作为响应内容。如果实际情况不同,请相应调整代码。

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

发表评论

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

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

相关阅读