我正在用 JAVA 构建我的 HTTP WEB 服务器。
如果客户端请求任何文件并且该文件在服务器的那个地方,那么服务器将该文件提供给客户端。我也做了这个代码,它工作正常。
显示上述功能的代码部分,
File targ = [CONTAINS ONE FILE]
PrintStream ps;
InputStream is = new FileInputStream(targ.getAbsolutePath());
while ((n = is.read(buf)) > 0) {
System.out.println(n);
ps.write(buf, 0, n);
}
但是现在为了优化我的代码,我用下面的代码替换了这段代码,
InputStream is = null;
BufferedReader reader = null;
String output = null;
is = new FileInputStream(targ.getAbsolutePath());
reader = new BufferedReader(new InputStreamReader(is));
while( (output = reader.readLine()) != null) {
System.out.println("new line");
//System.out.println(output);
ps.print(output);
}
但它有时会显示一个错误 为什么代码显示“错误 354 (net::ERR_CONTENT_LENGTH_MISMATCH):服务器意外关闭了连接。”
。我不明白,为什么会显示此错误。这个错误很奇怪,因为服务器显示 200
代码,这意味着该文件在那里。
请帮帮我
编辑编号1
char[] buffer = new char[1024*16];
int k = reader.read(buffer);
System.out.println("size : " + k);
do {
System.out.println("\tsize is : " + k);
//System.out.println(output);
ps.println(buffer);
}while( (k = reader.read(buffer)) != -1 );
这会打印所有文件,但对于较大的文件,它会显示不可读的字符。
它显示如下输出 (客户端浏览器的快照)
最佳答案
您执行 output = reader.readLine()
来获取数据,其中省略了换行符。然后你ps.print(output)
,所以换行符不会发送到客户端。
假设你读过这个
Hello\r\n
World\r\n
然后你发送这个:
Content-length: 14
HelloWorld
然后关闭连接,使浏览器感到困惑,因为它仍在等待其他 4 个字节。
我猜你必须使用 ps.println(output)
。
如果您正在监视网络流量,您就会看到这一点,这在编写或调试应该使用网络进行通信的服务器时非常有用。
无论如何,如果文件的换行符和系统不匹配(\n
vs \r\n
),这将导致麻烦。假设你有这个文件:
Hello\r\n
World\r\n
它的长度是 14 个字节。但是,当您的系统在打印时将换行符视为 \n
时,您使用 println()
的代码将打印此内容:
Hello\n
World\n
这是 12 个字节,而不是 14 个。你最好只打印你读到的内容。
关于sockets - 为什么代码显示 "Error 354 (net::ERR_CONTENT_LENGTH_MISMATCH): The server unexpectedly closed the connection.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16357848/