Java 编写一个简单的 HTTP 服务器,用于提供静态网页文件

import java.io.*;
import java.net.*;

public class HTTPServer {
    
    public static final int PORT = 8080;
    public static final String WEB_ROOT = "www/";

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(PORT);
            System.out.println("HTTP Server is running on port " + PORT);
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("Accepted connection from " + clientSocket.getInetAddress().getHostName());
                InputStream inputStream = clientSocket.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String request = reader.readLine();
                System.out.println("Received request: " + request);
                String[] tokens = request.split(" ");
                String filePath = WEB_ROOT + tokens[1];
                FileInputStream fileInputStream = null;
                boolean fileExists = true;
                try {
                    fileInputStream = new FileInputStream(filePath);
                } catch (FileNotFoundException e) {
                    fileExists = false;
                }
                String responseStatus = null;
                String responseBody = null;
                if (fileExists) {
                    responseStatus = "HTTP/1.1 200 OK";
                    responseBody = readFile(fileInputStream);
                } else {
                    responseStatus = "HTTP/1.1 404 Not Found";
                    responseBody = "<h1>404 Not Found</h1>";
                }
                String response = responseStatus + "\r\n" +
                                  "Content-Type: text/html\r\n" +
                                  "Content-Length: " + responseBody.length() + "\r\n" +
                                  "\r\n" + responseBody;
                OutputStream outputStream = clientSocket.getOutputStream();
                outputStream.write(response.getBytes());
                clientSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String readFile(FileInputStream fileInputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = fileInputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }
        return outputStream.toString();
    }
}

在上面的代码中,我们定义了一个名为 HTTPServer 的类,它使用 Java 的 Socket API 实现了一个简单的 HTTP 服务器。服务器监听 8080 端口,并在接收到客户端请求时提供静态网页文件。

在 main 方法中,我们首先创建一个 ServerSocket 对象,该对象绑定到端口 8080 并开始监听连接。然后,我们进入一个无限循环,在每次迭代中接受一个客户端连接,并读取其请求。我们从请求中提取文件路径,并尝试打开该文件以读取其内容。如果文件存在,则返回 HTTP 200 状态码和文件内容作为响应;否则,返回 HTTP 404 状态码和简单的“404 Not Found”消息。

最后,我们将响应发送回客户端,并关闭连接。在发送响应之前,我们需要将响应内容转换为字节数组,并计算内容长度和响应头部分。

要运行此代码,请将其保存在名为 HTTPServer.java 的文件中,并将 www/ 目录中的静态


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值