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 關注
- 181 瀏覽
添加回答
舉報