Using a Selector to Manage Non-Blocking Server Sockets
For more information about selectors, see
Using a Selector to Manage Non-Blocking Sockets.
This example creates two server sockets and registers them with
a selector. The example then uses the selector to listen for events.
try {
// Create the selector
Selector selector = Selector.open();
// Create two non-blocking server sockets on 80 and 81
ServerSocketChannel ssChannel1 = ServerSocketChannel.open();
ssChannel1.configureBlocking(false);
ssChannel1.socket().bind(new InetSocketAddress(80));
ServerSocketChannel ssChannel2 = ServerSocketChannel.open();
ssChannel2.configureBlocking(false);
ssChannel2.socket().bind(new InetSocketAddress(81));
// Register both channels with selector
ssChannel1.register(selector, SelectionKey.OP_ACCEPT);
ssChannel2.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
// Wait for an event
selector.select();
// Get list of selection keys with pending events
Iterator it = selector.selectedKeys().iterator();
// Process each key
while (it.hasNext()) {
// Get the selection key
SelectionKey selKey = (SelectionKey)it.next();
// Remove it from the list to indicate that it is being processed
it.remove();
// Check if it's a connection request
if (selKey.isAcceptable()) {
// Get channel with connection request
ServerSocketChannel ssChannel = (ServerSocketChannel)selKey.channel();
// See Accepting a Connection on a ServerSocketChannel
// for an example of accepting a connection request
}
}
}
} catch (IOException e) {
}
Post a comment