NIO accept() loop, traditional thread for processing
Hi folks,
I need to change a server so that it listens on multiple addresses and
ports, and behaves differently depending on which port is which. It
seems straightforward enough using nio, but I'd be most grateful if
someone would validate my approach.
I have followed standard tutorials to create ServerSocketChannels, set
them to non-blocking mode, and register them to a selector. Then I
loop around selector.select().
Here's the bit I want to validate:
while(stopped = false) {
selections = selector.select();
if(selections > 0) {
Set keys = selector.selectedKeys();
Iterator i = keys.iterator();
while(i.hasNext()) {
SelectionKey key = (SelectionKey) i.next();
ServerSocketChannel sch = (ServerSocketChannel) key.channel();
SocketChannel chan = sch.accept();
// chan.configureBlocking(true); // necessary? wise?
SessionHandler handler = new SessionHandler(chan.socket());
handler.start();
i.remove();
}
}
}
SessionHandler is a subclass of java.lang.Thread and has no NIO
related code in it. The toy server I've written in this way seems to
work, but do I need to worry about blocking when I'm handling serious
data? The existing code relies on blocking reads.
Also, is it safe to add a stop() method:
public void stop() {
stopped = true;
selector.wakeup();
}
?