Methods Summary |
---|
protected synchronized boolean | getDone()
return done;
|
protected abstract void | handleClient(java.nio.channels.SelectionKey key)
|
protected void | handleServer(java.nio.channels.SelectionKey key)
SocketChannel sc = channel.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
registeredClient(sc);
|
protected abstract void | registeredClient(java.nio.channels.SocketChannel sc)
|
public void | run()
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 void | startServer()
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 void | stopServer()
done = true;
channel.close();
|