Java Reference
In-Depth Information
"text/html; charset=utf-8" , body . length ());
}
out . write ( body );
out . flush ();
}
} catch ( IOException ex ) {
logger . log ( Level . WARNING ,
"Error talking to " + connection . getRemoteSocketAddress (), ex );
} finally {
try {
connection . close ();
}
catch ( IOException ex ) {}
}
}
private void sendHeader ( Writer out , String responseCode ,
String contentType , int length )
throws IOException {
out . write ( responseCode + "\r\n" );
Date now = new Date ();
out . write ( "Date: " + now + "\r\n" );
out . write ( "Server: JHTTP 2.0\r\n" );
out . write ( "Content-length: " + length + "\r\n" );
out . write ( "Content-type: " + contentType + "\r\n\r\n" );
out . flush ();
}
}
This server is functional but still rather austere. Here are a few features that could be
added:
• A server administration interface
• Support for the Java Servlet API
• Support for other request methods, such as POST , HEAD , and PUT
• Support for multiple document roots so individual users can have their own sites
Finally, spend a little time thinking about ways to optimize this server. If you really want
to use JHTTP to run a high-traffic site, there are a couple of things that can speed this
server up. The first thing to do is implement smart caching. Keep track of the requests
you've received and store the data from the most frequently requested files in a Map so
that they're kept in memory. Use a low-priority thread to update this cache. You can
also try using nonblocking I/O and channels instead of threads and streams. We'll ex‐
plore this possibility in Chapter 11 .
Search WWH ::




Custom Search