HttpServerpublic class HttpServer extends Object Simple-minded HTTP server using MappedByteBuffers.
This example will be expanded significantly
Created: April 2002 |
Fields Summary |
---|
private static final int | DEFAULT_PORT | private static final String | DEFAULT_ROOT_DIR | private static final String | LINE_SEP | private static final String | HTTP_HDR | private ByteBuffer | staticHdr | private Charset | utf8 | private Pattern | space | private String | rootDir | private CharBuffer | cbtemp | private ByteBuffer | dynHdr |
Methods Summary |
---|
public static void | main(java.lang.String[] argv)
// ---------------------------------------------------------
int port = DEFAULT_PORT;
if (argv.length != 0) {
port = Integer.parseInt (argv [0]);
}
HttpServer server = new HttpServer();
System.out.println ("Starting server on port " + port);
server.runServer (port);
| public void | runServer(int port)
ServerSocketChannel ssc = ServerSocketChannel.open();
ByteBuffer temp = ByteBuffer.allocate (1024 * 10);
ssc.socket().bind (new InetSocketAddress (port));
while (true) {
SocketChannel socket = ssc.accept();
temp.clear();
socket.read (temp);
temp.flip();
CharBuffer cb = utf8.decode (temp);
System.out.println ("cb = " + cb);
String [] tokens = space.split (cb, 3);
String filename = rootDir + tokens [1];
FileInputStream fis = new FileInputStream (filename);
FileChannel fc = fis.getChannel();
sendFile (fc, socket,
URLConnection.guessContentTypeFromName (filename));
fc.close();
fis.close();
socket.close();
}
| private void | sendBuffer(java.nio.ByteBuffer data, java.nio.channels.GatheringByteChannel channel, java.lang.String contentType)
ByteBuffer [] buffers = { staticHdr, dynHdr, data };
staticHdr.rewind();
cbtemp.clear();
cbtemp.put ("Content-Length: " + data.limit());
cbtemp.put (LINE_SEP);
cbtemp.put ("Content-Type: ");
cbtemp.put (contentType);
cbtemp.put (LINE_SEP);
cbtemp.put (LINE_SEP);
cbtemp.flip();
buffers [1] = utf8.encode (cbtemp);
while (channel.write (buffers) != 0) {
// nothing
}
| public void | sendFile(java.nio.channels.FileChannel file, java.nio.channels.GatheringByteChannel out, java.lang.String contentType)
MappedByteBuffer fileData = file.map (MapMode.READ_ONLY,
0, file.size());
sendBuffer (fileData, out, contentType);
|
|