Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将htm文件发送到套接字_Java_Sockets - Fatal编程技术网

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

Java 如何将htm文件发送到套接字,java,sockets,Java,Sockets,我正在尝试将此htm文件发送到web浏览器,并让浏览器显示文件的内容。当我运行我的代码时,所发生的一切就是浏览器显示htm文件的名称,而不显示其他内容 try { BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(),

我正在尝试将此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协议。

您需要打开并读取文件,而不仅仅是发送名称:您认为
输出了什么。write(myFile)
是这样做的,您为什么这么认为?看来你错了,所以请重新思考你在做什么,例如,阅读
write(…)
所做的以及
文件
对象是什么的文档。无论在何处,都不应使用这两种方法。HTTP中的行终止符指定为
\r\n
,而不是系统上生成的任何
println()
。好的,谢谢您的评论。我想
out.write(行+“\r\n”)应该修复它吗?我还提到了代码是一个想法,没有考虑HTTP协议。是的,标题行也是如此。很抱歉out.write()的内容。我在胡闹,当我发布这个问题时,我忘了把它放回out.println(),我不知道如何编辑我的帖子。是的!非常感谢:)