Java Reference
In-Depth Information
Because this array will only be read from after it's been initialized, you can reuse it for
multiple channels. However, each channel will get its own buffer filled with the contents
of this array. You'll stuff the buffer with the first 72 bytes of the rotation array, then add
a carriage return/linefeed pair to break the line. Then you'll flip the buffer so it's ready
for draining, and attach it to the channel's key:
ByteBuffer buffer = ByteBuffer . allocate ( 74 );
buffer . put ( rotation , 0 , 72 );
buffer . put (( byte ) '\r' );
buffer . put (( byte ) '\n' );
buffer . flip ();
key2 . attach ( buffer );
To check whether anything is ready to be acted on, call the selector's select() method.
For a long-running server, this normally goes in an infinite loop:
while ( true ) {
selector . select ();
// process selected keys...
}
Assuming the selector does find a ready channel, its selectedKeys() method returns
a java.util.Set containing one SelectionKey object for each ready channel. Other‐
wise, it returns an empty set. In either case, you can loop through this with a
java.util.Iterator :
Set < SelectionKey > readyKeys = selector . selectedKeys ();
Iterator iterator = readyKeys . iterator ();
while ( iterator . hasNext ()) {
SelectionKey key = iterator . next ();
// Remove key from set so we don't process it twice
iterator . remove ();
// operate on the channel...
}
Removing the key from the set tells the Selector that you've dealt with it, and the
Selector doesn't need to keep giving it back every time you call select() . The Selec
tor will add the channel back into the ready set when select() is called again if the
channel becomes ready again. It's really important to remove the key from the ready set
here, though.
If the ready channel is the server channel, the program accepts a new socket channel
and adds it to the selector. If the ready channel is a socket channel, the program writes
as much of the buffer as it can onto the channel. If no channels are ready, the selector
waits for one. One thread, the main thread, processes multiple simultaneous connec‐
tions.
In this case, it's easy to tell whether a client or a server channel has been selected because
the server channel will only be ready for accepting and the client channels will only be
Search WWH ::




Custom Search