Java Reference
In-Depth Information
port
=
80
;
}
try
{
JHTTP
webserver
=
new
JHTTP
(
docroot
,
port
);
webserver
.
start
();
}
catch
(
IOException
ex
)
{
logger
.
log
(
Level
.
SEVERE
,
"Server could not start"
,
ex
);
}
}
}
The
main()
method of the
JHTTP
class sets the document root directory from
args[0]
. The port is read from
args[1]
or 80 is used for a default. Then a new
JHTTP
object is constructed and started.
JHTTP
creates a thread pool to handle requests and
repeatedly accepts incoming connections. You submit one
RequestProcessor
thread
per incoming connection into the pool.
Each connection is handled by the
run()
method of the
RequestProcessor
class shown
in
Example 9-13
. It gets input and output streams from the socket and chains them to
a reader and a writer. The reader reads the first line of the client request to determine
the version of HTTP that the client supports—you want to send a MIME header only
if this is HTTP/1.0 or later—and the requested file. Assuming the method is
GET
, the
file that is requested is converted to a filename on the local filesystem. If the file requested
is a directory (i.e., its name ends with a slash), you add the name of an index file. You
use the canonical path to make sure that the requested file doesn't come from outside
the document root directory. Otherwise, a sneaky client could walk all over the local
filesystem by including
..
in URLs to walk up the directory hierarchy. This is all you'll
need from the client, although a more advanced web server, especially one that logged
hits, would read the rest of the MIME header the client sends.
Next, the requested file is opened and its contents are read into a
byte
array. If the HTTP
version is 1.0 or later, you write the appropriate MIME headers on the output stream.
To figure out the content type, you call the
URLConnection.getFileNameMap().get
ContentTypeFor(fileName)
method to map file extensions such as
.html
onto MIME
types such as text/html. The
byte
array containing the file's contents is written onto the
output stream and the connection is closed. If the file cannot be found or opened, you
send the client a 404 response instead. If the client sends a method you don't support,
such as
POST
, you send back a 501 error. If an exception occurs, you log it, close the
connection, and continue.
Example 9-13. The runnable class that handles HTTP requests
import
java.io.*
;
import
java.net.*
;
import
java.nio.file.Files
;
import
java.util.*
;