gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:16:56 24 4
gpt4 key购买 nike

我正在尝试将此 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");
}

最佳答案

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

...
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 协议(protocol)。

关于java - 如何将 htm 文件发送到套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54622558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com