如何将htm文件发送到套接字

时间:2019-02-11 00:29:19

标签: java sockets

我正在尝试将此htm文件发送到Web浏览器,并让浏览器显示该文件的内容。当我运行代码时,所有发生的就是浏览器显示htm文件的名称,而没有其他显示。

try 
    {
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        String input = in.readLine();

        while (!input.isEmpty()) 
        {
            System.out.println("\tserver read a line: " + input);
            input = in.readLine();
        }

        System.out.println("");

        File myFile = new File ("hello.htm");

        out.println("HTTP/1.1 200 OK");
        out.println("Content-Type: text/html");
        out.println("\r\n");
        out.write(myFile);
        out.flush();
        out.close();
    }

    catch(Exception e)
    {
        System.out.println("\ncaught exeception: " + e + "\n");
    }

1 个答案:

答案 0 :(得分:1)

您实际上需要将文件的内容写入流:

...
BufferedReader in2 = new BufferedReader(new FileReader(myFile));
out.write("HTTP/1.1 200 OK\r\n");
out.write("Content-Type: text/html\r\n");
//Tell the end user how much data you are sending
out.write("Content-Length: " + myFile.length() + "\r\n");
//Indicates end of headers
out.write("\r\n");
String line;
while((line = in2.readLine()) != null) {
    //Not sure if you should use out.println or out.write, play around with it.
    out.write(line + "\r\n");
}
//out.write(myFile); Remove this
out.flush();
out.close();
...

上面的代码只是您应该真正做什么的一个想法。它考虑了HTTP协议。