FileDocCategorySizeDatePackage
TCPNIOServer.javaAPI DocExample2611Sun Dec 07 10:44:00 GMT 2003javathreads.examples.ch12

TCPNIOServer

public abstract class TCPNIOServer extends Object implements Runnable

Fields Summary
protected ServerSocketChannel
channel
private boolean
done
protected Selector
selector
protected int
port
Constructors Summary
Methods Summary
protected synchronized booleangetDone()

        return done;
    
protected abstract voidhandleClient(java.nio.channels.SelectionKey key)

protected voidhandleServer(java.nio.channels.SelectionKey key)

         SocketChannel sc = channel.accept();
         sc.configureBlocking(false);
         sc.register(selector, SelectionKey.OP_READ);
         registeredClient(sc);
     
protected abstract voidregisteredClient(java.nio.channels.SocketChannel sc)

public voidrun()

        try {
            startServer();
        } catch (IOException ioe) {
            System.out.println("Can't start server:  " + ioe);
            return;
        }
        while (!getDone()) {
            try {
                selector.select();
            } catch (IOException ioe) {
                System.err.println("Server error: " + ioe);
                return;
            }
            Iterator it = selector.selectedKeys().iterator();
            while (it.hasNext()) {
                SelectionKey key = (SelectionKey) it.next();
                if (key.isReadable() || key.isWritable()) {
                    // Key represents a socket client
                    try {
                        handleClient(key);
                    } catch (IOException ioe) {
                        // Client disconnected
                        key.cancel();
                    }
                } else if (key.isAcceptable()) {
                    try {
                        handleServer(key);
                    } catch (IOException ioe) {
                        // Accept error; treat as fatal
                        throw new IllegalStateException(ioe);
                    }
                } else System.out.println("unknown key state");
                it.remove();
            }
        }
    
public voidstartServer()


         
        channel = ServerSocketChannel.open();
        channel.configureBlocking(false);
        ServerSocket server = channel.socket();
        server.bind(new InetSocketAddress(port));
        selector = Selector.open();
        channel.register(selector, SelectionKey.OP_ACCEPT);
    
public synchronized voidstopServer()

        done = true;
        channel.close();