Когда вы тестируете свой сервер с помощью веб-браузера, вам нужно отправить действительный HTTP-запрос, включая заголовки HTTP, которые содержатся в вашей жестко запрограммированной части.
Итак, вам просто нужно добавить вывод части заголовка просто перед печатью содержимого файла.
Также вам необходимо собрать информацию о размере файла и отправить заголовок "Content-Length: " + file_size + "\r\n"
.
Существует ошибка с закрытием printWriter перед завершением sh читая файл страницы, вам необходимо закрыть его после l oop:
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();
}