1 回答
TA贡献1788条经验 获得超4个赞
当您使用 Web 浏览器测试服务器时,您需要发送有效的 HTTP 请求,其中包括硬编码部分中提供的 HTTP 标头。
因此,您应该在打印文件内容之前添加标题部分的输出。
您还需要收集有关文件大小的信息并发送"Content-Length: " + file_size + "\r\n"标头。
在读完页面文件之前关闭 printWriter 存在一个错误,您需要在循环之后关闭它:
while(line != null)//repeat till the file is empty
{
printWriter.println(line);//print current line
printWriter.flush();// I have also tried putting this outside the while loop right before
printWriter.close() // BUG: no ";" and closing printWriter too early
line = reader.readLine();//read next line
}
因此,将文件发送到客户端的更新方法如下:
private void sendPage(Socket client) throws Exception {
System.out.println("Page writter called");
File index = new File("index.html");
PrintWriter printWriter = new PrintWriter(client.getOutputStream());// Make a writer for the output stream to
// the client
BufferedReader reader = new BufferedReader(new FileReader(index));// grab a file and put it into the buffer
// print HTTP headers
printWriter.println("HTTP/1.1 200 OK");
printWriter.println("Content-Type: text/html");
printWriter.println("Content-Length: " + index.length());
printWriter.println("\r\n");
String line = reader.readLine();// line to go line by line from file
while (line != null)// repeat till the file is read
{
printWriter.println(line);// print current line
line = reader.readLine();// read next line
}
reader.close();// close the reader
printWriter.close();
}
- 1 回答
- 0 关注
- 111 浏览
添加回答
举报