FileDocCategorySizeDatePackage
HttpServer.javaAPI DocExample3431Wed May 15 18:45:48 BST 2002com.ronsoft.books.nio.channels

HttpServer

public class HttpServer extends Object
Simple-minded HTTP server using MappedByteBuffers. This example will be expanded significantly Created: April 2002
author
Ron Hitchens (ron@ronsoft.com)
version
$Id: HttpServer.java,v 1.2 2002/05/16 01:45:48 ron Exp $

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
Constructors Summary
Methods Summary
public static voidmain(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 voidrunServer(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 voidsendBuffer(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 voidsendFile(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);