Java Reference
In-Depth Information
System.out.println ( " Client message: " + client - str);
// Split the message into substrings.
String [] tokens = client - str.split("");
// Check that the message has a minimun number of words
// and that the first word is the GET command.
if ((tokens.length >= 2) &&
tokens[0].equals ("GET")) {
String file - name = tokens[1];
// Ignore the leading "/" on the file name.
if (file - name.startsWith ("/"))
file - name = file - name.substring (1);
// If no file name is there, use index.html default.
if (file - name.endsWith ("/") || file - name.equals (""))
file - name = file - name + " index.html " ;
// Check if the file is hypertext or plain text
String content - type;
if (file - name.endsWith ( " .html " ) ||
file - name.endsWith ( " .htm " )) {
content - type =" text/html " ;
}
...
If the request from the client is valid, we then read the local file that the client
is requesting and return it to the client. As shown in the following code, to
read the file we first obtain a FileInputStream for the file. We send text
messages back to the client using the PrintWriter methods. We note that the
PrintWriter methods don't throw IOException and instead the class offers
the checkError() method, which returns true if an IOException occurred.
For the sake of brevity, we did not check for errors after every print invocation.
(In the DataWorker class in Chapter 15, we place the print invocations in utility
methods that check for errors and throw exceptions when they occur.)
The line HTTP/1.0 200 OK \ r \ n gives the protocol and version num-
ber of the return message followed by the 200 code number that indicates that
the file has been found successfully and will be sent. This is followed by the file's
modification date, an identification of the server, the length of the file and the file
type (e.g. text/html ). Finally, the whole file is sent in one big byte array
via the write() method of OutputStream .
If the file is not available, the program sends the 404 Object Not
Found error message, which is a common one for web users. If the request
line had problems, a 400 Bad Request error message is sent.
 
Search WWH ::




Custom Search