Java 服务器将 html 页面从文件发送到浏览器

Java server send html page from file to browser

我一直在尝试制作一个显示文件索引的 java 服务器。我正在创建一个 SocketServer 并将其连接到一个端口。然后创建一个充当客户端的 Socket 并创建一个连接到客户端的套接字输出流的 PrintWriter。如果我将页面硬编码到 PrintWriter,一切正常,但是当我尝试逐行读取文件并将其发送到 PrintWriter 时,没有显示任何内容。

package com.github.masonnoyce;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Date;
import java.io.File;
import java.nio.file.Files;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.PrintWriter;


public class AServer
{
    public static void main (String[] args) throws Exception
    {
        AServer server = new AServer();
        int portNumber = 8080;
        //create server socket and say that it is running
        final ServerSocket myServer = new ServerSocket(portNumber);
        System.out.println("I have Connected To Port " + portNumber);

        boolean running = true;
        while(running)
        {
                //See if anyone connects
                try(Socket client = myServer.accept())
                {                    
                    server.sendPage(client);
                }
                catch(IOException e)
                {
                    System.out.println("Something went wrong streaming the page");
                    System.exit(1);
                }
        }
        try
        {
            myServer.close();
        }
        finally
        {
            System.out.println("Server Is now closed");
        }        
    }
    private void sendPage(Socket client) throws Exception
    {
        System.out.println("Page writter called");

        PrintWriter printWriter = new PrintWriter(client.getOutputStream());//Make a writer for the output stream to the client
        BufferedReader reader = new BufferedReader(new FileReader("path/to/index.html"));//grab a file and put it into the buffer
        String line = reader.readLine();//line to go line by line from file
        while(line != null)//repeat till the file is empty
        {
            printWriter.println(line);//print current line
            printWriter.flush();// I have also tried putting this outside the while loop right before 
            printWriter.close()
            line = reader.readLine();//read next line
        }
        reader.close();//close the reader
        printWriter.close();//Close the writer
//***********This section works if I replace the While loop With It**********//
//            printWriter.println("HTTP/1.1 200 OK");
//            printWriter.println("Content-Type: text/html");
//            printWriter.println("\r\n");
//            printWriter.println("<p> Hello world </p>");
//            printWriter.flush();//needed to actually send the data to the client
//            printWriter.close();//Close the writer
//************Above is the Hardcoding I was talking about****************************// 
    }    
} 

现在我知道服务器应该 运行 在线程上,从技术上讲它目前永远不会退出,并且不需要某些导入。我现在不担心那个。我只需要弄清楚为什么 PrintWriter 不喜欢在浏览器上显示 html 时使用文件。我已经创建了一个调试 PrintWriter,它写入文件以测试我是否有正确的文件位置并且它可以使用它。

当您使用 Web 浏览器测试您的服务器时,您需要发送一个有效的 HTTP 请求,包括在您的硬编码部分中提供的 HTTP headers。

因此,您应该在打印文件内容之前添加 header 部分的输出。

还需要收集文件大小的信息,发送"Content-Length: " + file_size + "\r\n"header.

在读取完页面文件之前关闭printWriter有一个错误,你需要在循环之后关闭它:

    while(line != null)//repeat till the file is empty
    {
        printWriter.println(line);//print current line
        printWriter.flush();// I have also tried putting this outside the while loop right before 
        printWriter.close() // BUG: no ";" and closing printWriter too early
        line = reader.readLine();//read next line
    }

因此,将文件发送到客户端的更新方法如下:

    private void sendPage(Socket client) throws Exception {
        System.out.println("Page writter called");

        File index = new File("index.html");

        PrintWriter printWriter = new PrintWriter(client.getOutputStream());// Make a writer for the output stream to
                                                                            // the client
        BufferedReader reader = new BufferedReader(new FileReader(index));// grab a file and put it into the buffer
        // print HTTP headers
        printWriter.println("HTTP/1.1 200 OK");
        printWriter.println("Content-Type: text/html");
        printWriter.println("Content-Length: " + index.length());
        printWriter.println("\r\n");
        String line = reader.readLine();// line to go line by line from file
        while (line != null)// repeat till the file is read
        {
            printWriter.println(line);// print current line

            line = reader.readLine();// read next line
        }
        reader.close();// close the reader
        printWriter.close();
    }