如何从服务器发送 html 文件以在客户端浏览器中打开?

How can I send a html file from the server to be opened in the client's browser?

我创建了一个正常运行的 Web 服务器,目前,我必须将文件中的 html 代码完全粘贴到服务器程序中,以便客户端浏览器读取 html 代码。我想要一种更简单的方法,我可以创建一个指向服务器目录中 html 文件的变量,以便服务器可以发送该文件中写入的任何代码。

这是我的主服务器class:

package myserver.pkg1.pkg0;

import java.net.*;

public class Server implements Runnable {

    protected boolean isStopped = false;
    protected static ServerSocket server = null;

    public static void main(String[] args) {

        try {

            server = new ServerSocket(9000);
            System.out.println("Server is ON and listening for incoming requests...");
            Thread t1 = new Thread(new Server());
            t1.start();

        } catch(Exception e) {
            System.out.println("Could not open port 9000.\n" + e);
        }

    }

    @Override
    public void run() {

        while(!isStopped) {

            try {
                Socket client = server.accept();
                System.out.println(client.getRemoteSocketAddress() + " has connected.");
                Thread t2 = new Thread(new Server());
                t2.start();
                new Thread(new Worker(client)).start();
            } catch(Exception e) {
                System.out.println(e);
            }

        }

    }

}

如您所见,服务器接受请求后,客户端套接字变量被转发给新的 class Worker。

这是工人 class:

package myserver.pkg1.pkg0;

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

public class Worker implements Runnable {

    protected Socket client;

    public Worker(Socket client) {
        this.client = client;
    }

    @Override
    public void run() {

        try {
            PrintWriter out = new PrintWriter(client.getOutputStream());       
            out.println("HTTP/1.1 200 OK");
            out.println("Content-type: text/html");
            out.println("\r\n");
            //In this line I used out.println("full html code"); but I'd like a simpler way where it can search for the html file in the directory and send it.
            out.flush();
            out.close();
            client.close();

        } catch(Exception e) {
            System.out.println(e);
        }

    }

}

Worker class 处理将在客户端浏览器上看到的所有输出,我希望它是 html 文件的结果。

您可以将文件 "index.html" 放在您的类路径中并执行

    InputStream in = this.getClass().getClassLoader()
            .getResourceAsStream("index.html");
    String s = new BufferedReader(new InputStreamReader(in))
            .lines().collect(Collectors.joining("\n"));
    out.println(s);