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

标签 java html file bufferedreader printwriter

我一直在尝试制作一个显示文件索引的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,它写入一个文件来测试我是否有正确的文件位置并且它可以使用它。

最佳答案

当您使用网络浏览器测试服务器时,您需要发送有效的 HTTP 请求,其中包括硬编码部分中提供的 HTTP header 。

因此,您应该在打印文件内容之前添加 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();
    }

关于Java服务器将html页面从文件发送到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61258777/

相关文章:

java - java代码的重构

html - 复杂的 CSS 导航错误

javascript - 使用按钮创建 HTML 元素

Java:访问与 .jar 位于同一目录中的文件

iPhone - 存储与文件相关的字符串数据的位置

c# - C#程序中的System.IO.Compression.FileSystem.dll

java - 如何获取我当前的时间

java - 为什么 ant 每次运行都要编译所有的类?

java - 如何统计相同的json值并将其显示在textview中?

html - 检查嵌入式YouTube视频是否已经开始