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

标签 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");
    }

最佳答案

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

...
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/

相关文章:

java - 验证不同的验证组 JSF 2.0

c - 如何知道套接字何时完成读取

java - 此转储中 netty 的内存使用情况正常吗?

编译器对 sendto 调用中的参数 6 发出警告

python - 使用 python 创建 SSL 套接字

java - Android应用使用Socket收发消息 :

c++ - 发送的字节数多于我应该通过套接字接收的字节数

java - 如何分割 "^A"字符

java - 图像特征提取

java - 写一个方程