Java Reference
In-Depth Information
response code; this is only provided to support very old browsers that don't do redi‐
rection automatically, as well as a few security paranoids who have configured their
browsers not to redirect automatically.
The main() method provides a very simple interface that reads the URL of the new site
to redirect connections to and the local port to listen on. It uses this information to
construct a Redirector object. Then it invokes start() . If the port is not specified,
Redirector listens on port 80. If the site is omitted, Redirector prints an error message
and exits.
The start() method of Redirector binds the server socket to the port, prints a brief
status message, and then enters an infinite loop in which it listens for connections. Every
time a connection is accepted, the resulting Socket object is used to construct a Redi
rectThread . This RedirectThread is then started. All further interaction with the client
takes place in this new thread. The start() method then simply waits for the next
incoming connection.
The run() method of RedirectThread does most of the work. It begins by chaining a
Writer to the Socket 's output stream and a Reader to the Socket 's input stream. Both
input and output are buffered. Then the run() method reads the first line the client
sends. Although the client will probably send a whole MIME header, you can ignore
that. The first line contains all the information you need. The line looks something like
this:
GET /directory/filename.html HTTP/1.0
It is possible that the first word will be POST or PUT instead or that there will be no HTTP
version. The second “word” is the file the client wants to retrieve. This must begin with
a slash (/). Browsers are responsible for converting relative URLs to absolute URLs that
begin with a slash; the server does not do this. The third word is the version of the HTTP
protocol the browser understands. Possible values are nothing at all (pre-HTTP/1.0
browsers), HTTP/1.0, or HTTP/1.1.
To handle a request like this, Redirector ignores the first word. The second word is
attached to the URL of the target server (stored in the field newSite ) to give a full
redirected URL. The third word is used to determine whether to send a MIME header;
MIME headers are not used for old browsers that do not understand HTTP/1.0. If there
is a version, a MIME header is sent; otherwise, it is omitted.
Sending the data is almost trivial. The Writer out is used. Because all the data you send
is pure ASCII, the exact encoding isn't too important. The only trick here is that the
end-of-line character for HTTP requests is \r\n- a carriage return followed by a line‐
feed.
The next lines each send one line of text to the client. The first line printed is:
HTTP / 1.0 302 FOUND
Search WWH ::




Custom Search