Article Source: ASPCN Author: Sun Wen
A simple Web server
A simple Web server will be built from listing 9.2. Of course, the method and response events must also be improved. A simple server does not parse and store the request headers. The new Web server will analyze and store requests for future processing. To achieve this goal, You must have a class that contains HTTP requests.
HttpRequest class
Listing 9.5 Lists a complete HttpRequest class. This class must include all the information required by a request header.
List of 9.5.HTTPrequest classes.
Import java.io.*;
Import java.util.*;
Import java.net.*;
Import Namevalue;
/**
* This class has all the information for an HTTP request
*/
public class HttpRequest
{
public String version;
Public String method;
public String file;
Public Socket Clientsocket;
public DataInputStream Inbound;
Public Namevalue headerpairs[];
/**
* Create an instance of this class
*/
Public HttpRequest ()
{
Version = NULL;
method = null;
FILE = null;
Clientsocket = null;
inbound = null;
inbound = null;
Headerpairs = new Namevalue[0];
}
/**
* Add a name/value pair to the core array
*/
public void Addnamevalue (string name, String value)
{
Try
{
Namevalue temp[] = new namevalue[headerpairs.length + 1];
System.arraycopy (headerpairs, 0, temp, 0, headerpairs.length);
temp[Headerpairs.length] = new Namevalue (name, value);
Headerpairs = temp;
}
catch (NullPointerException NPE)
{
System.out.println ("NullPointerException while adding Name-value:
"+ NPE);
}
}
/**
* Return this class as a string
*/
Public String toString ()
{
String s = method + "" + file + "" + version + \ n;
for (int x = 0; x < Headerpairs.length + +)
s + + headerpairs[x] + "\ n";
return s;
}
}
The Namevalue class simply stores two strings: name and value. When a new pair is to be added, a new array is assigned. The new array accepts the old array and the new member. The old array is then overwritten by a new object.