In the following paragraphs, let's take a look at these three classes.
Httpserver class
The Httpserver class represents a Web server and can be serviced for those static resources found in the public static directory Web_root and its subdirectories. Web_root is initialized in the following ways:
public static final String Web_root =
System.getproperty ("User.dir") + File.separator + "Webroot";
This code indicates a Webroot directory containing static resources that can be used to test the application. The servlet container can also be found in this directory.
To request a static resource, enter the following address or URL in the browser:
Http://machineName:port/staticResource
MachineName is the computer name or IP address that runs the application. If your browser is on the same machine, you can use localhost as the machine name. The port is 8080. StaticResource is the requested folder name and must be located in the Web-root directory.
Inevitably, if you use the same computer to test the application, you want to send a index.html file to the Httpserver request, then use the following URL:
Http://localhost:8080/index.html
To stop the server, you can send a shutdown command. The command is defined by the static Shutdown_command variable in the Httpserver class:
private static final String Shutdown_command = "/shutdown";
Therefore, to stop the service, you can use the command:
Http://localhost:8080/SHUTDOWN
Now let's take a look at the await method mentioned earlier. An explanation is given in the following list of programs.
Listing 1.1. The Httpserver class ' await method
public void await () {
ServerSocket serversocket = null;
int port = 8080;
try {
ServerSocket = new ServerSocket (port, 1,
Inetaddress.getbyname ("127.0.0.1"));
}
catch (IOException e) {
E.printstacktrace ();
System.exit (1);
}
Loop waiting for a request
while (!shutdown) {
Socket socket = NULL;
InputStream input = null;
OutputStream output = null;
try {
Socket = Serversocket.accept ();
input = Socket.getinputstream ();
Output = Socket.getoutputstream ();
Create Request object and parse
Request Request = new request (input);
Request.parse ();
Create Response Object
Response Response = new Response (output);
Response.setrequest (Request);
Response.sendstaticresource ();
Close the socket
Socket.close ();
Check if the previous URI is a shutdown command
shutdown = Request.geturi (). Equals (Shutdown_command);
}
catch (Exception e) {
E.printstacktrace ();
Continue
}
}
}
The await method starts by creating a ServerSocket instance. And then it goes into a while loop:
ServerSocket = new ServerSocket (
Port, 1, Inetaddress.getbyname ("127.0.0.1"));
...
Loop waiting for a request
while (!shutdown) {
...
}
Socket = Serversocket.accept ();
After a request is received, the await method obtains the Java.io.InputStream and Java.io.OutputStream objects from the socket instance returned by the Accept method.