Java Reference
In-Depth Information
is read from the third command-line argument, if present. Otherwise, UTF-8 is as‐
sumed. Then these values are used to construct a SingleFileHTTPServer object and
start it.
The main() method is only one possible interface. You could easily use this class as part
of some other program. If you added a setter method to change the content, you could
easily use it to provide simple status information about a running server or system.
However, that would raise some additional issues of thread safety that Example 9-10
doesn't have to address because the data is immutable.
Here's what you see when you connect to this server via Telnet (the specifics depend on
the exact server and file):
% telnet macfaq . dialup . cloud9 . net 80
Trying 168.100 . 203.234 ...
Connected to macfaq . dialup . cloud9 . net .
Escape character is ' ^] ' .
GET / HTTP / 1.0
HTTP / 1.0 200 OK
Server: OneFile 2.0
Content - length: 959
Content - type: text / html ; charset = UTF - 8
& lt ;! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN" & gt ;
& lt ; HTML & gt ;
& lt ; HEAD & gt ;
& lt ; TITLE & gt ; Under Construction & lt ;/ TITLE & gt ;
& lt ;/ HEAD & gt ;
& lt ; BODY & gt ;
...
A Redirector
Redirection is another simple but useful application for a special-purpose HTTP server.
In this section, you develop a server that redirects users from one website to another—
for example, from cnet.com to www.cnet.com . Example 9-11 reads a URL and a port
number from the command line, opens a server socket on the port, and redirects all
requests that it receives to the site indicated by the new URL using a 302 FOUND code.
In this example, I chose to use a new thread rather than a thread pool for each connec‐
tion. This is perhaps a little simpler to code and understand but somewhat less efficient.
Example 9-11. An HTTP redirector
import java.io.* ;
import java.net.* ;
import java.util.* ;
import java.util.logging.* ;
public class Redirector {
Search WWH ::




Custom Search