I have a simple HTML server program that listens on port 8000 for a request. I want to be able to request an HTML file from the server program and send the requested HTML back to the browser. Currently the server receives the request and parses the requested filename from the request, and will even print the contents of the html file to the console. However, when I try to print the HTML file contents to the connection’s socket (back to the browser) nothing happens; the browser just continues loading.
My server class is relatively simple and just creates instances of this runnable class, RequestHandler, for each connection:
package server;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class RequestHandler extends Thread {
Object block;
ServerSocket serverSocket;
BufferedReader socketReader;
PrintWriter socketWriter;
public RequestHandler(Object block, ServerSocket serverSocket){
this.block = block;
this.serverSocket = serverSocket;
}
@Override
public void run() {
try{
System.out.println("Waiting for request...");
Socket clientSocket = serverSocket.accept();
System.out.println("Connection made.");
synchronized(block){
System.out.print("Notifying server thread...");
block.notify();
System.out.println("...done");
System.out.println();
}
socketReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
socketWriter = new PrintWriter(clientSocket.getOutputStream(), true);
String input;
while((input = socketReader.readLine()) != null){
// System.out.println(input);
if(input.startsWith("GET")){
getResource(input);
}
}
}catch(IOException e){
System.out.println("IOException!");
e.printStackTrace();
}
}
public void getResource(String getRequest){
String[] parts = getRequest.split("\\s+");
String filename = parts[1].substring(1);
System.out.println(filename);
File resource = new File(filename);
sendResponse(resource);
}
public void sendResponse(File resource){
System.out.println(resource.getAbsolutePath());
Scanner fileReader;
try {
fileReader = new Scanner(resource);
while(fileReader.hasNext()){
String line = fileReader.nextLine();
System.out.println(line);
socketWriter.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("File not found!");
e.printStackTrace();
}
}
}
What should you always do when you’re done writing to or reading from a stream? (I know the answer to your question, but I’m asking this question because you labeled your question as “homework”)