Java Reference
In-Depth Information
line = in.readLine();
System.out.println(line);
} while (line.trim().length() > 0);
Once the first blank line is hit, the program is done reading the HTTP headers. Because
this server only supports GET requests, the program is also done reading the HTTP request.
Now it is time to write the HTTP response. The following lines of code write a simple HTML
message that says “Hello World” to the browser.
// Write the HTTP response.
out.println("HTTP/1.1 200 OK");
out.println("");
out.println("<html>");
out.println("<head><title>Simple Web Server</title></head>");
out.println("<body>");
out.println("<h1>Hello World</h1>");
out.println("<//body>");
out.println("</html>");
Now that the message has been written, it is time to close the streams. The following
lines of code do this.
// Close everything up.
out.close();
in.close();
socket.close();
The above recipe showed how to create a simple web server. In addition to this basic
functionality, this recipe can be expanded to be a custom web server that will respond to dif-
ferent requests. For example, a web server could be constructed to give information about
how a process is running or other status information collected by the computer.
Most web servers simply present files to the browser. However, Recipe 1.1 generated its
response internally. This can be a very useful technique to display status information for your
web server. The next recipe, Recipe 1.2, shows how to create a web server that will allow ac-
cess to files.
Recipe #1.2: File Based Web Server
This recipe shows how to create a very common sort of web server. This web sever ex-
poses a directory tree to the Internet. This directory tree is called the “HTTP root”, or “web
root”. Files placed into this directory will be accessed by web browsers. A default file, named
index.html , should be placed into this directory. This file is displayed when the user
browses to the directory. The index.html file usually has links to the other files in that
directory, and serves as a starting point.
Search WWH ::




Custom Search