I tried to implement a simple HTTP server with socket in Java. What it does is to accept a file name from the client browser, opens that file on the disk and prints it out in the browser. My current code is shown below:
public class HTTPServer {
public String getFirstLine(Scanner s) {
String line = "";
if (s.hasNextLine()) {
line = s.nextLine();
}
if (line.startsWith("GET /")) {
return line;
}
return null;
}
public String getFilePath(String s) {
int beginIndex = s.indexOf("/");
int endIndex = s.indexOf(" ", beginIndex);
return s.substring(beginIndex + 1, endIndex);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
Socket clientSocket = null;
int serverPort = 7777; // the server port
try {
ServerSocket listenSocket = new ServerSocket(serverPort);
while (true) {
clientSocket = listenSocket.accept();
Scanner in;
PrintWriter out;
HTTPServer hs;
in = new Scanner(clientSocket.getInputStream());
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())));
hs = new HTTPServer();
// get the first line
String httpGetLine = hs.getFirstLine(in);
if (httpGetLine != null) {
// parse the file path
String filePath = hs.getFilePath(httpGetLine);
// open the file and read it
File f = new File(filePath);
if (f.exists()) {
// if the file exists, response to the client with its content
out.println("HTTP/1.1 200 OK\n\n");
out.flush();
BufferedReader br = new BufferedReader(new FileReader(filePath));
String fileLine;
while ((fileLine = br.readLine()) != null) {
out.println(fileLine);
out.flush();
}
} else {
out.println("HTTP/1.1 404 NotFound\n\nFile " + filePath + " not found.");
out.flush();
}
}
}
} catch (IOException e) {
System.out.println("IO Exception:" + e.getMessage());
} finally {
try {
if (clientSocket != null) {
clientSocket.close();
}
} catch (IOException e) {
// ignore exception on close
}
}
}
}
After I run it in NetBeans, I open the browser and visit "localhost:7777/hello.html" (hello.html is a file in the project folder). It just shows the page is loading. Only after I stop my server in NetBeans will the content of hello.html be shown in the browser.
I want my server to work indefinitely, respond to GET requests one after another and display to the client the file content. I'm not sure which parts of my code should be put in the while(true)
loop and which not.
You need to close the socket when you're done with it.