FileDocCategorySizeDatePackage
LargerHttpd.javaAPI DocExample3956Sat Apr 23 22:35:38 BST 2005None

LargerHttpd

public class LargerHttpd extends Object

Fields Summary
Selector
clientSelector
Constructors Summary
Methods Summary
voidacceptClient(java.nio.channels.ServerSocketChannel ssc)

		SocketChannel clientSocket = ssc.accept();
		clientSocket.configureBlocking(false);
		SelectionKey key = 
			clientSocket.register( clientSelector, SelectionKey.OP_READ );
		HttpdConnection client = new HttpdConnection( clientSocket );
		key.attach( client );
	
voidhandleClient(java.nio.channels.SelectionKey key)

		HttpdConnection client = (HttpdConnection)key.attachment();
		if ( key.isReadable() )
			client.read( key );
		else 
			client.write( key );
		clientSelector.wakeup();
	
public static voidmain(java.lang.String[] argv)

		new LargerHttpd().run( Integer.parseInt(argv[0]), 3/*threads*/ );
	
public voidrun(int port, int threads)

		clientSelector = Selector.open();
		ServerSocketChannel ssc = ServerSocketChannel.open();
		ssc.configureBlocking(false);
		InetSocketAddress sa = 
			new InetSocketAddress( InetAddress.getLocalHost(), port );
		ssc.socket().bind( sa );
		ssc.register( clientSelector, SelectionKey.OP_ACCEPT );
	
		Executor executor = Executors.newFixedThreadPool( threads );

		while ( true ) 
		try {
			while ( clientSelector.select(100) == 0 );
			Set<SelectionKey> readySet = clientSelector.selectedKeys();
			for(Iterator<SelectionKey> it=readySet.iterator(); it.hasNext();) {
				final SelectionKey key = it.next();
				it.remove();
				if ( key.isAcceptable() ) 
					acceptClient( ssc );
				else {
					key.interestOps( 0 );
					executor.execute( new Runnable() {
						public void run() { 
							try { 
								handleClient( key ); 
							} catch ( IOException e) { System.out.println(e); }
						}
					} );
				}
			}
		} catch ( IOException e ) { System.out.println(e); }